11import logging
22from fastapi import APIRouter , File , UploadFile , HTTPException , Depends , Header , Path , status
33from fastapi .responses import FileResponse
4- from app .models .schemas import (
5- HandwrittenUploadResponse ,
6- HandwrittenListResponse ,
7- HandwrittenStatusResponse ,
8- HandwrittenDeleteResponse ,
9- HandwrittenDocument
10- )
4+ from app .models .schemas import HandwrittenUploadResponse , HandwrittenListResponse , HandwrittenStatusResponse , HandwrittenDeleteResponse , HandwrittenDocument
115from app .celery_tasks .document_tasks import process_handwritten_document_task
126from app .services .handwritten_storage import get_handwritten_storage , HandwrittenDocumentStorage
137from celery .result import AsyncResult
@@ -27,49 +21,39 @@ async def upload_handwritten_document(
2721 Upload a handwritten PDF document for processing to LaTeX.
2822 """
2923 logger .info (f"Received handwritten document upload: { file .filename } for group { group_id } " )
30-
24+
3125 if not file .filename :
3226 raise HTTPException (status_code = 400 , detail = "No file name provided." )
33-
34- if not file .filename .lower ().endswith ('.pdf' ):
35- raise HTTPException (
36- status_code = 400 ,
37- detail = "Only PDF files are supported for handwritten document processing."
38- )
39-
27+
28+ if not file .filename .lower ().endswith (".pdf" ):
29+ raise HTTPException (status_code = 400 , detail = "Only PDF files are supported for handwritten document processing." )
30+
4031 try :
4132 # Read file content
4233 contents = await file .read ()
4334 logger .info (f"Read { len (contents )} bytes from uploaded file: { file .filename } " )
44-
35+
4536 if not contents :
4637 raise HTTPException (status_code = 400 , detail = "Uploaded file content is empty." )
47-
38+
4839 # Start Celery task first to get the real task ID
4940 task = process_handwritten_document_task .delay (contents , file .filename , group_id , None )
50-
41+
5142 # Use the Celery task ID for storage
5243 celery_task_id = task .id
53-
44+
5445 # Store metadata using the Celery task ID
5546 storage .store_document_metadata (celery_task_id , group_id , file .filename )
56-
47+
5748 logger .info (f"Started handwritten processing task { celery_task_id } for { file .filename } in group { group_id } " )
58-
59- return HandwrittenUploadResponse (
60- task_id = celery_task_id ,
61- filename = file .filename ,
62- message = "Handwritten document uploaded and processing started in background."
63- )
64-
49+
50+ return HandwrittenUploadResponse (task_id = celery_task_id , filename = file .filename , message = "Handwritten document uploaded and processing started in background." )
51+
6552 except HTTPException as http_exc :
6653 raise http_exc
6754 except Exception as e :
6855 logger .error (f"Unexpected error during handwritten document upload of { file .filename } : { e } " , exc_info = True )
69- raise HTTPException (
70- status_code = 500 ,
71- detail = f"An unexpected server error occurred: { str (e )} "
72- )
56+ raise HTTPException (status_code = 500 , detail = f"An unexpected server error occurred: { str (e )} " )
7357 finally :
7458 await file .close ()
7559
@@ -83,18 +67,15 @@ def list_handwritten_documents(
8367 List all handwritten documents for a group, separated by processing status.
8468 """
8569 logger .info (f"Listing handwritten documents for group { group_id } " )
86-
70+
8771 try :
8872 documents = storage .get_documents_by_group (group_id )
89-
73+
9074 processing = [doc for doc in documents if doc .status in ["PENDING" , "PROCESSING" ]]
9175 completed = [doc for doc in documents if doc .status in ["SUCCESS" , "FAILURE" ]]
92-
93- return HandwrittenListResponse (
94- processing = processing ,
95- completed = completed
96- )
97-
76+
77+ return HandwrittenListResponse (processing = processing , completed = completed )
78+
9879 except Exception as e :
9980 logger .error (f"Error listing handwritten documents for group { group_id } : { e } " , exc_info = True )
10081 raise HTTPException (status_code = 500 , detail = "Failed to retrieve handwritten documents." )
@@ -109,16 +90,16 @@ def get_handwritten_status(
10990 Get the processing status of a handwritten document.
11091 """
11192 logger .info (f"Checking status for handwritten document task { task_id } " )
112-
93+
11394 try :
11495 # Get from storage first
11596 document = storage .get_document (task_id )
11697 if not document :
11798 raise HTTPException (status_code = 404 , detail = "Document not found." )
118-
99+
119100 # Check Celery task status
120101 task_result = AsyncResult (task_id , app = process_handwritten_document_task .app )
121-
102+
122103 # Update status if task is complete
123104 if task_result .ready ():
124105 if task_result .successful ():
@@ -127,21 +108,14 @@ def get_handwritten_status(
127108 # Refresh document data
128109 document = storage .get_document (task_id )
129110 elif task_result .failed ():
130- error_result = {
131- "status" : "FAILURE" ,
132- "error_message" : str (task_result .result ) if task_result .result else "Unknown error"
133- }
111+ error_result = {"status" : "FAILURE" , "error_message" : str (task_result .result ) if task_result .result else "Unknown error" }
134112 storage .update_document_status (task_id , error_result )
135113 document = storage .get_document (task_id )
136-
114+
137115 return HandwrittenStatusResponse (
138- task_id = document .task_id ,
139- status = document .status ,
140- original_filename = document .original_filename ,
141- processed_filename = document .processed_filename ,
142- error_message = document .error_message
116+ task_id = document .task_id , status = document .status , original_filename = document .original_filename , processed_filename = document .processed_filename , error_message = document .error_message
143117 )
144-
118+
145119 except HTTPException as http_exc :
146120 raise http_exc
147121 except Exception as e :
@@ -159,35 +133,25 @@ def download_processed_document(
159133 Download the processed LaTeX PDF document.
160134 """
161135 logger .info (f"Download request for processed document { task_id } from group { group_id } " )
162-
136+
163137 try :
164138 document = storage .get_document (task_id )
165139 if not document :
166140 raise HTTPException (status_code = 404 , detail = "Document not found." )
167-
141+
168142 # Validate group membership
169143 if document .group_id != group_id :
170- raise HTTPException (
171- status_code = 403 ,
172- detail = "Access denied. You can only download documents from your own group."
173- )
174-
144+ raise HTTPException (status_code = 403 , detail = "Access denied. You can only download documents from your own group." )
145+
175146 if document .status != "SUCCESS" :
176- raise HTTPException (
177- status_code = 400 ,
178- detail = f"Document is not ready for download. Status: { document .status } "
179- )
180-
147+ raise HTTPException (status_code = 400 , detail = f"Document is not ready for download. Status: { document .status } " )
148+
181149 file_path = storage .get_file_path (task_id , "processed" )
182150 if not file_path or not file_path .exists ():
183151 raise HTTPException (status_code = 404 , detail = "Processed file not found." )
184-
185- return FileResponse (
186- path = str (file_path ),
187- media_type = "application/pdf" ,
188- filename = document .processed_filename or f"processed_{ document .original_filename } "
189- )
190-
152+
153+ return FileResponse (path = str (file_path ), media_type = "application/pdf" , filename = document .processed_filename or f"processed_{ document .original_filename } " )
154+
191155 except HTTPException as http_exc :
192156 raise http_exc
193157 except Exception as e :
@@ -204,25 +168,22 @@ def delete_handwritten_document(
204168 Delete a handwritten document and all its associated files.
205169 """
206170 logger .info (f"Delete request for handwritten document { task_id } " )
207-
171+
208172 try :
209173 document = storage .get_document (task_id )
210174 if not document :
211175 raise HTTPException (status_code = 404 , detail = "Document not found." )
212-
176+
213177 # Delete the document
214178 success = storage .delete_document (task_id )
215-
179+
216180 if success :
217- return HandwrittenDeleteResponse (
218- task_id = task_id ,
219- message = "Document successfully deleted."
220- )
181+ return HandwrittenDeleteResponse (task_id = task_id , message = "Document successfully deleted." )
221182 else :
222183 raise HTTPException (status_code = 500 , detail = "Failed to delete document." )
223-
184+
224185 except HTTPException as http_exc :
225186 raise http_exc
226187 except Exception as e :
227188 logger .error (f"Error deleting document { task_id } : { e } " , exc_info = True )
228- raise HTTPException (status_code = 500 , detail = "Failed to delete document." )
189+ raise HTTPException (status_code = 500 , detail = "Failed to delete document." )
0 commit comments