alisaadhq commited on
Commit
3befaa5
·
verified ·
1 Parent(s): c149ecb

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +11 -22
main.py CHANGED
@@ -2,7 +2,6 @@ from fastapi import FastAPI, UploadFile, HTTPException
2
  import subprocess
3
  import tempfile
4
  import os
5
- import uuid
6
  import pdfplumber
7
  import io
8
 
@@ -12,26 +11,14 @@ app = FastAPI()
12
  async def health_check():
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,
31
- os.path.splitext(os.path.basename(input_path))[0] + ".txt"
32
  )
33
- with open(txt_path, "r", encoding="utf-8") as f:
34
- return f.read()
 
35
 
36
  @app.post("/extract-text")
37
  async def extract_text(file: UploadFile):
@@ -44,9 +31,11 @@ async def extract_text(file: UploadFile):
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 = []
 
2
  import subprocess
3
  import tempfile
4
  import os
 
5
  import pdfplumber
6
  import io
7
 
 
11
  async def health_check():
12
  return {"status": "ok"}
13
 
14
+ def convert_with_pandoc(input_path: str) -> str:
15
+ result = subprocess.run(
16
+ ["pandoc", input_path, "-t", "plain"],
17
+ capture_output=True, text=True, timeout=20 # عادي جدًا 20 ثانية كافية
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  )
19
+ if result.returncode != 0:
20
+ raise Exception(result.stderr)
21
+ return result.stdout
22
 
23
  @app.post("/extract-text")
24
  async def extract_text(file: UploadFile):
 
31
  with open(input_path, "wb") as f:
32
  f.write(content)
33
  try:
34
+ text = convert_with_pandoc(input_path)
35
  except subprocess.TimeoutExpired:
36
+ raise HTTPException(504, "Pandoc conversion timed out.")
37
+ except Exception as e:
38
+ raise HTTPException(500, f"Pandoc error: {str(e)}")
39
 
40
  elif filename.endswith('.pdf'):
41
  text_parts = []