from fastapi import FastAPI, UploadFile, HTTPException import subprocess import tempfile import os import pdfplumber import io app = FastAPI() @app.get("/") async def health_check(): return {"status": "ok"} def convert_with_pandoc(input_path: str) -> str: result = subprocess.run( ["pandoc", input_path, "-t", "plain"], capture_output=True, text=True, timeout=20 # عادي جدًا 20 ثانية كافية ) if result.returncode != 0: raise Exception(result.stderr) return result.stdout @app.post("/extract-text") async def extract_text(file: UploadFile): content = await file.read() filename = file.filename.lower() if filename.endswith('.docx'): with tempfile.TemporaryDirectory() as tmp: input_path = os.path.join(tmp, file.filename) with open(input_path, "wb") as f: f.write(content) try: text = convert_with_pandoc(input_path) except subprocess.TimeoutExpired: raise HTTPException(504, "Pandoc conversion timed out.") except Exception as e: raise HTTPException(500, f"Pandoc error: {str(e)}") elif filename.endswith('.pdf'): text_parts = [] with pdfplumber.open(io.BytesIO(content)) as pdf: for page in pdf.pages: page_text = page.extract_text() if page_text: text_parts.append(page_text) for table in page.extract_tables(): for row in table: row_text = " | ".join(str(c) for c in row if c) if row_text: text_parts.append(row_text) text = "\n".join(text_parts) else: raise HTTPException(400, "Unsupported file type. Only .docx and .pdf allowed.") if not text.strip(): raise HTTPException(422, "Could not extract any text from file.") return {"filename": file.filename, "extractedText": text}