Perform OCR task on uploaded file
(file: UploadFile, task_type: str)
| 559 | await asyncio.get_event_loop().run_in_executor(None, create_zip_sync) |
| 560 | |
| 561 | async def perform_ocr_task(file: UploadFile, task_type: str) -> TaskResponse: |
| 562 | """Perform OCR task on uploaded file""" |
| 563 | try: |
| 564 | monkey_ocr_model = model_manager.get_model() |
| 565 | supports_async = model_manager.get_async_support() |
| 566 | model_lock = model_manager.get_model_lock() |
| 567 | |
| 568 | if not monkey_ocr_model: |
| 569 | raise HTTPException(status_code=500, detail="Model not initialized") |
| 570 | |
| 571 | # Validate file type |
| 572 | allowed_extensions = {'.pdf', '.jpg', '.jpeg', '.png'} |
| 573 | file_ext = Path(file.filename).suffix.lower() |
| 574 | if file_ext not in allowed_extensions: |
| 575 | raise HTTPException( |
| 576 | status_code=400, |
| 577 | detail=f"Unsupported file type: {file_ext}. Allowed: {', '.join(allowed_extensions)}" |
| 578 | ) |
| 579 | |
| 580 | # Save uploaded file temporarily with unique name |
| 581 | import uuid |
| 582 | unique_suffix = str(uuid.uuid4())[:8] |
| 583 | |
| 584 | with tempfile.NamedTemporaryFile(delete=False, suffix=file_ext, prefix=f"ocr_{unique_suffix}_") as temp_file: |
| 585 | content = await file.read() |
| 586 | temp_file.write(content) |
| 587 | temp_file_path = temp_file.name |
| 588 | |
| 589 | try: |
| 590 | # Create output directory with unique name |
| 591 | output_dir = tempfile.mkdtemp(prefix=f"monkeyocr_{task_type}_{unique_suffix}_") |
| 592 | |
| 593 | # Use optimized async single task recognition |
| 594 | result_dir = await async_single_task_recognition(temp_file_path, output_dir, task_type) |
| 595 | |
| 596 | # Read result file |
| 597 | def read_result_sync(): |
| 598 | result_files = [f for f in os.listdir(result_dir) if f.endswith(f'_{task_type}_result.md')] |
| 599 | if not result_files: |
| 600 | raise Exception("No result file generated") |
| 601 | |
| 602 | result_file_path = os.path.join(result_dir, result_files[0]) |
| 603 | with open(result_file_path, 'r', encoding='utf-8') as f: |
| 604 | return f.read() |
| 605 | |
| 606 | content = await asyncio.get_event_loop().run_in_executor(None, read_result_sync) |
| 607 | |
| 608 | return TaskResponse( |
| 609 | success=True, |
| 610 | task_type=task_type, |
| 611 | content=content, |
| 612 | message=f"{task_type.capitalize()} extraction completed successfully" |
| 613 | ) |
| 614 | |
| 615 | finally: |
| 616 | # Clean up temporary file |
| 617 | try: |
| 618 | os.unlink(temp_file_path) |
no test coverage detected