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from langdetect import detect
|
| 8 |
+
from multilingual_pdf2text.pdf2text import PDF2Text
|
| 9 |
+
from multilingual_pdf2text.models.document_model.document import Document
|
| 10 |
+
|
| 11 |
+
import pdfplumber
|
| 12 |
+
import docx2txt
|
| 13 |
+
import shutil
|
| 14 |
+
import subprocess
|
| 15 |
+
|
| 16 |
+
print("π Checking if Tesseract OCR is installed...")
|
| 17 |
+
|
| 18 |
+
tess_path = shutil.which("tesseract")
|
| 19 |
+
if tess_path:
|
| 20 |
+
print(f"β
Tesseract found at: {tess_path}")
|
| 21 |
+
try:
|
| 22 |
+
version = subprocess.check_output(["tesseract", "--version"]).decode()
|
| 23 |
+
print(f"π§ Tesseract version:\n{version}")
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"β οΈ Tesseract found but failed to run: {e}")
|
| 26 |
+
else:
|
| 27 |
+
print("β Tesseract not found. Arabic PDF extraction will likely fail.")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# --- Config ---
|
| 31 |
+
FLOWISE_URL = "https://siraflowappl.happywave-0e1819cd.uaenorth.azurecontainerapps.io/api/v1/prediction/5f2aa074-ae2e-4b06-a4a2-6f8dccbe59bb"
|
| 32 |
+
COUNTRIES = ["USA", "Germany", "UAE", "Turkey", "Jordan"]
|
| 33 |
+
LANGUAGES = ["English", "Arabic"]
|
| 34 |
+
|
| 35 |
+
logging.basicConfig(level=logging.INFO)
|
| 36 |
+
|
| 37 |
+
# --- File Text Extraction ---
|
| 38 |
+
def extract_text_from_file(file_path: str) -> str:
|
| 39 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
if ext == ".pdf":
|
| 43 |
+
with pdfplumber.open(file_path) as pdf:
|
| 44 |
+
extracted = "\n".join(
|
| 45 |
+
page.extract_text() for page in pdf.pages if page.extract_text()
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
sample = extracted[:1000].strip()
|
| 49 |
+
lang = detect(sample) if sample else "unknown"
|
| 50 |
+
|
| 51 |
+
if lang == "ar" or not sample:
|
| 52 |
+
arabic_doc = Document(document_path=file_path, language="ara")
|
| 53 |
+
pdf2text = PDF2Text(document=arabic_doc)
|
| 54 |
+
extracted = pdf2text.extract()
|
| 55 |
+
|
| 56 |
+
if isinstance(extracted, list):
|
| 57 |
+
if isinstance(extracted[0], dict):
|
| 58 |
+
return "\n".join(item.get("text", "") for item in extracted)
|
| 59 |
+
elif isinstance(extracted[0], str):
|
| 60 |
+
return "\n".join(extracted)
|
| 61 |
+
else:
|
| 62 |
+
return "[Error: Unexpected Arabic extractor format.]"
|
| 63 |
+
elif isinstance(extracted, str):
|
| 64 |
+
return extracted
|
| 65 |
+
else:
|
| 66 |
+
return "[Error: Unrecognized Arabic extraction output.]"
|
| 67 |
+
|
| 68 |
+
return extracted or "[Warning: No readable text found in PDF.]"
|
| 69 |
+
|
| 70 |
+
elif ext == ".docx":
|
| 71 |
+
return docx2txt.process(file_path)
|
| 72 |
+
|
| 73 |
+
elif ext == ".txt":
|
| 74 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 75 |
+
return f.read()
|
| 76 |
+
|
| 77 |
+
else:
|
| 78 |
+
return "[Unsupported file format.]"
|
| 79 |
+
|
| 80 |
+
except Exception as e:
|
| 81 |
+
logging.exception("Failed to extract text.")
|
| 82 |
+
return f"[Error reading file: {e}]"
|
| 83 |
+
|
| 84 |
+
# --- Flowise Query ---
|
| 85 |
+
def send_to_flowise(file, country: str, language: str) -> str:
|
| 86 |
+
if not file or not country or not language:
|
| 87 |
+
return "β Please upload a contract, select a country, and choose a response language."
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
contract_text = extract_text_from_file(file.name).strip()
|
| 91 |
+
if not contract_text:
|
| 92 |
+
return "β οΈ No content extracted from the uploaded file."
|
| 93 |
+
|
| 94 |
+
prompt = f"""Please audit the following employment contract in light of {country} labor law.
|
| 95 |
+
Only refer to the provided law document (do not use external knowledge).
|
| 96 |
+
Is the contract compliant? Provide reasoning and highlight any issues, and suggest improvements.
|
| 97 |
+
Be precise and don't miss any details in the contract.
|
| 98 |
+
Please respond in {language}.
|
| 99 |
+
<CONTRACT START>
|
| 100 |
+
{contract_text}
|
| 101 |
+
<CONTRACT END>"""
|
| 102 |
+
|
| 103 |
+
payload = {
|
| 104 |
+
"question": prompt,
|
| 105 |
+
"chatId": str(uuid.uuid4())
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
res = requests.post(FLOWISE_URL, json=payload, timeout=300)
|
| 109 |
+
logging.info("π Flowise response: %s", res.text)
|
| 110 |
+
|
| 111 |
+
if res.status_code != 200:
|
| 112 |
+
return f"β Flowise error {res.status_code}: {res.text}"
|
| 113 |
+
|
| 114 |
+
return res.json().get("text", "β οΈ Flowise returned no text.")
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logging.exception("Flowise request failed.")
|
| 118 |
+
return f"β Connection error: {e}"
|
| 119 |
+
|
| 120 |
+
# --- Gradio UI ---
|
| 121 |
+
with gr.Blocks(title="Contract Auditor") as demo:
|
| 122 |
+
gr.Markdown("## π Contract Auditor")
|
| 123 |
+
|
| 124 |
+
with gr.Row():
|
| 125 |
+
country_dropdown = gr.Dropdown(choices=COUNTRIES, label="π Select Country", interactive=True)
|
| 126 |
+
language_dropdown = gr.Dropdown(choices=LANGUAGES, label="π£οΈ Select Response Language", interactive=True)
|
| 127 |
+
|
| 128 |
+
file_input = gr.File(
|
| 129 |
+
label="π Upload a contract file",
|
| 130 |
+
file_types=[".pdf", ".docx", ".txt"],
|
| 131 |
+
type="filepath"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
submit_btn = gr.Button("π€ Audit Contract")
|
| 135 |
+
output = gr.Textbox(label="π§ Audit Result", lines=12)
|
| 136 |
+
|
| 137 |
+
submit_btn.click(
|
| 138 |
+
fn=send_to_flowise,
|
| 139 |
+
inputs=[file_input, country_dropdown, language_dropdown],
|
| 140 |
+
outputs=output
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
demo.launch(share=True)
|