Spaces:
Sleeping
Sleeping
File size: 2,028 Bytes
ba12d77 de65ef9 ba12d77 de65ef9 3befaa5 de65ef9 3befaa5 ba12d77 de65ef9 f51152d 3befaa5 f51152d 3befaa5 ba12d77 de65ef9 ba12d77 de65ef9 ba12d77 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 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} |