LiamKhoaLe commited on
Commit
f91bb25
·
1 Parent(s): e5d6418

Upd upload stream

Browse files
Files changed (1) hide show
  1. app/routers/import_doc.py +62 -1
app/routers/import_doc.py CHANGED
@@ -20,7 +20,8 @@ class ImportRequest(BaseModel):
20
  source: str
21
  ref: dict
22
 
23
- # Embedding, query and PDF saver to buckets
 
24
  @router.post("")
25
  async def import_book(req: ImportRequest):
26
  logger.info(f"📥 Received import request: {req.dict()}")
@@ -105,6 +106,66 @@ async def import_book(req: ImportRequest):
105
  "uri": uri
106
  }
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  # Fetch textbook on id
110
  @router.get("/textbook/{doc_id}")
 
20
  source: str
21
  ref: dict
22
 
23
+
24
+ # Online stream: Embedding, query and PDF saver to buckets
25
  @router.post("")
26
  async def import_book(req: ImportRequest):
27
  logger.info(f"📥 Received import request: {req.dict()}")
 
106
  "uri": uri
107
  }
108
 
109
+
110
+ # File upload stream: Embedding, query and PDF saver to buckets
111
+ from fastapi import UploadFile, File, Form
112
+ @router.post("/upload")
113
+ async def upload_book(
114
+ file: UploadFile = File(...),
115
+ title: str = Form(...),
116
+ candidate_id: str = Form(...),
117
+ source: str = Form("manual") # Optional default source
118
+ ):
119
+ logger.info(f"📤 Received direct upload for: {candidate_id} ({title})")
120
+ db = get_db()
121
+ # Insert placeholder document first
122
+ placeholder_doc = {
123
+ "_id": candidate_id,
124
+ "title": title,
125
+ "status": "PENDING",
126
+ "metadata": {
127
+ "source": source,
128
+ "ref": {"upload": True}
129
+ }
130
+ }
131
+ await db.documents.replace_one({"_id": candidate_id}, placeholder_doc, upsert=True)
132
+ # Save uploaded file to temp
133
+ file_path = f"/tmp/{candidate_id}.pdf"
134
+ try:
135
+ async with aiofiles.open(file_path, 'wb') as out_file:
136
+ content = await file.read()
137
+ await out_file.write(content)
138
+ logger.info(f"✅ Uploaded PDF temporarily saved to {file_path}")
139
+ except Exception as e:
140
+ logger.error(f"🚨 Failed to save uploaded file: {e}")
141
+ raise HTTPException(500, "Failed to save uploaded PDF")
142
+ # Save to buckets
143
+ try:
144
+ grid_fs_bucket = get_gridfs()
145
+ with open(file_path, "rb") as f:
146
+ await grid_fs_bucket.upload_from_stream(f"{candidate_id}.pdf", f)
147
+ await save_to_textbook_fs(candidate_id, file_path)
148
+ os.remove(file_path)
149
+ except Exception as e:
150
+ logger.error(f"💥 Failed to upload to GridFS: {e}")
151
+ raise HTTPException(500, "Storage failed")
152
+ # Update metadata and trigger ingestion
153
+ await db.documents.update_one(
154
+ {"_id": candidate_id},
155
+ {"$set": {"status": "DOWNLOADING"}}
156
+ )
157
+ asyncio.create_task(parse_and_index(candidate_id))
158
+ logger.info(f"📚 Direct upload {candidate_id} queued for indexing")
159
+ # Final block
160
+ return {
161
+ "status": "QUEUED",
162
+ "id": candidate_id,
163
+ "title": title,
164
+ "source": source,
165
+ "documentId": candidate_id,
166
+ "uri": f"/import/textbook/{candidate_id}"
167
+ }
168
+
169
 
170
  # Fetch textbook on id
171
  @router.get("/textbook/{doc_id}")