Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -2,6 +2,7 @@ from fastapi import FastAPI, UploadFile, HTTPException
|
|
| 2 |
import subprocess
|
| 3 |
import tempfile
|
| 4 |
import os
|
|
|
|
| 5 |
import pdfplumber
|
| 6 |
import io
|
| 7 |
|
|
@@ -12,12 +13,18 @@ async def health_check():
|
|
| 12 |
return {"status": "ok"}
|
| 13 |
|
| 14 |
def convert_with_libreoffice(input_path: str, output_dir: str) -> str:
|
|
|
|
|
|
|
|
|
|
| 15 |
subprocess.run(
|
| 16 |
[
|
| 17 |
-
"libreoffice", "--headless", "--
|
|
|
|
|
|
|
| 18 |
"--outdir", output_dir, input_path
|
| 19 |
],
|
| 20 |
-
check=True,
|
|
|
|
| 21 |
)
|
| 22 |
txt_path = os.path.join(
|
| 23 |
output_dir,
|
|
@@ -36,7 +43,10 @@ async def extract_text(file: UploadFile):
|
|
| 36 |
input_path = os.path.join(tmp, file.filename)
|
| 37 |
with open(input_path, "wb") as f:
|
| 38 |
f.write(content)
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
elif filename.endswith('.pdf'):
|
| 42 |
text_parts = []
|
|
|
|
| 2 |
import subprocess
|
| 3 |
import tempfile
|
| 4 |
import os
|
| 5 |
+
import uuid
|
| 6 |
import pdfplumber
|
| 7 |
import io
|
| 8 |
|
|
|
|
| 13 |
return {"status": "ok"}
|
| 14 |
|
| 15 |
def convert_with_libreoffice(input_path: str, output_dir: str) -> str:
|
| 16 |
+
# بروفايل منفصل لكل تحويل، عشان نتجنب تعارض الـ lock بين الطلبات المتزامنة
|
| 17 |
+
unique_profile = f"/tmp/lo_profile_{uuid.uuid4().hex}"
|
| 18 |
+
|
| 19 |
subprocess.run(
|
| 20 |
[
|
| 21 |
+
"libreoffice", "--headless", "--norestore", "--nolockcheck",
|
| 22 |
+
f"-env:UserInstallation=file://{unique_profile}",
|
| 23 |
+
"--convert-to", "txt:Text",
|
| 24 |
"--outdir", output_dir, input_path
|
| 25 |
],
|
| 26 |
+
check=True,
|
| 27 |
+
timeout=120 # رفعناها من 60 لـ 120 ثانية
|
| 28 |
)
|
| 29 |
txt_path = os.path.join(
|
| 30 |
output_dir,
|
|
|
|
| 43 |
input_path = os.path.join(tmp, file.filename)
|
| 44 |
with open(input_path, "wb") as f:
|
| 45 |
f.write(content)
|
| 46 |
+
try:
|
| 47 |
+
text = convert_with_libreoffice(input_path, tmp)
|
| 48 |
+
except subprocess.TimeoutExpired:
|
| 49 |
+
raise HTTPException(504, "LibreOffice conversion timed out. Try again (cold start issue).")
|
| 50 |
|
| 51 |
elif filename.endswith('.pdf'):
|
| 52 |
text_parts = []
|