Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -228,53 +228,95 @@ def to_pdf(file_path):
|
|
228 |
|
229 |
@app.post("/process_document")
|
230 |
async def process_document(
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
):
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
278 |
|
279 |
# Initialize models
|
280 |
model_init = init_model()
|
|
|
228 |
|
229 |
@app.post("/process_document")
|
230 |
async def process_document(
|
231 |
+
file: UploadFile = File(...),
|
232 |
+
end_pages: int = 10,
|
233 |
+
is_ocr: bool = False,
|
234 |
+
layout_mode: str = "doclayout_yolo",
|
235 |
+
formula_enable: bool = True,
|
236 |
+
table_enable: bool = False,
|
237 |
+
language: str = "auto"
|
238 |
):
|
239 |
+
try:
|
240 |
+
print(f"\n=== НАЧАЛО ОБРАБОТКИ ДОКУМЕНТА ===")
|
241 |
+
print(f"Имя файла: {file.filename}")
|
242 |
+
print(f"Параметры: end_pages={end_pages}, is_ocr={is_ocr}, language={language}")
|
243 |
+
|
244 |
+
temp_path = f"/tmp/{file.filename}"
|
245 |
+
try:
|
246 |
+
with open(temp_path, "wb") as buffer:
|
247 |
+
content = await file.read()
|
248 |
+
buffer.write(content)
|
249 |
+
print(f"Файл сохранен: {temp_path}")
|
250 |
+
except Exception as e:
|
251 |
+
print(f"Ошибка при сохранении файла: {str(e)}")
|
252 |
+
raise
|
253 |
+
|
254 |
+
def extract_text_pymupdf(pdf_path):
|
255 |
+
try:
|
256 |
+
doc = fitz.open(pdf_path)
|
257 |
+
print(f"Открыт PDF, всего страниц: {doc.page_count}")
|
258 |
+
|
259 |
+
text = ""
|
260 |
+
for page_num in range(min(end_pages, doc.page_count)):
|
261 |
+
try:
|
262 |
+
page = doc[page_num]
|
263 |
+
blocks = page.get_text("blocks")
|
264 |
+
blocks.sort(key=lambda b: (b[1], b[0]))
|
265 |
+
for b in blocks:
|
266 |
+
text += b[4] + "\n"
|
267 |
+
print(f"Обработана страница {page_num + 1}")
|
268 |
+
except Exception as page_error:
|
269 |
+
print(f"Ошибка при обработке страницы {page_num + 1}: {str(page_error)}")
|
270 |
+
|
271 |
+
doc.close()
|
272 |
+
print(f"Извлечено {len(text)} символов текста")
|
273 |
+
return text
|
274 |
+
except Exception as e:
|
275 |
+
print(f"Ошибка при извлечении текста: {str(e)}")
|
276 |
+
return str(e)
|
277 |
+
|
278 |
+
source_4 = extract_text_pymupdf(temp_path) or ""
|
279 |
+
print(f"\nРазмер извлеченного текста: {len(source_4)} символов")
|
280 |
+
print(f"Первые 200 символов:\n{source_4[:200]}")
|
281 |
+
|
282 |
+
try:
|
283 |
+
os.remove(temp_path)
|
284 |
+
print("Временный файл удален")
|
285 |
+
except Exception as e:
|
286 |
+
print(f"Не удалось удалить временный файл: {str(e)}")
|
287 |
+
|
288 |
+
if not source_4.strip():
|
289 |
+
error_msg = "Не удалось извлечь текст из документа"
|
290 |
+
print(error_msg)
|
291 |
+
return JSONResponse(
|
292 |
+
status_code=422,
|
293 |
+
content={
|
294 |
+
"error": error_msg,
|
295 |
+
"details": "Извлеченный текст пуст"
|
296 |
+
}
|
297 |
+
)
|
298 |
+
|
299 |
+
print("\n=== ВОЗВРАЩАЕМЫЙ JSON ===")
|
300 |
+
response_json = {"text": source_4}
|
301 |
+
print(json.dumps(response_json, indent=2, ensure_ascii=False)[:500] + "...")
|
302 |
+
print("\n=== УСПЕШНОЕ ��АВЕРШЕНИЕ ОБРАБОТКИ ===")
|
303 |
+
|
304 |
+
return JSONResponse(response_json)
|
305 |
+
|
306 |
+
except Exception as e:
|
307 |
+
error_msg = f"Критическая ошибка при обработке документа: {str(e)}\nTraceback: {traceback.format_exc()}"
|
308 |
+
print(error_msg)
|
309 |
+
return JSONResponse(
|
310 |
+
status_code=500,
|
311 |
+
content={
|
312 |
+
"error": error_msg,
|
313 |
+
"details": {
|
314 |
+
"error_type": type(e).__name__,
|
315 |
+
"error_message": str(e),
|
316 |
+
"file_name": file.filename if file else None
|
317 |
+
}
|
318 |
+
}
|
319 |
+
)
|
320 |
|
321 |
# Initialize models
|
322 |
model_init = init_model()
|