rosolsharairh commited on
Commit
e85e038
Β·
verified Β·
1 Parent(s): 253cb36
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import uuid
4
+ import os
5
+ import pdfplumber
6
+ import docx2txt
7
+ import logging
8
+ import shutil
9
+ from langdetect import detect
10
+ from multilingual_pdf2text.pdf2text import PDF2Text
11
+ from multilingual_pdf2text.models.document_model.document import Document
12
+
13
+ logging.basicConfig(level=logging.INFO)
14
+
15
+ FLOWISE_URL = "http://localhost:3000/api/v1/prediction/3d1eebaf-31ee-44d6-94bc-4457948f5240"
16
+ COUNTRIES = ["USA", "Germany", "UAE", "Turkey", "Jordan"]
17
+ LANGUAGES = ["Arabic", "English", "German"]
18
+
19
+ # Tesseract availability check
20
+ print("πŸ” Checking if Tesseract OCR is installed...")
21
+ tess_path = shutil.which("tesseract")
22
+ if tess_path:
23
+ print(f"βœ… Tesseract found at: {tess_path}")
24
+ else:
25
+ print("❌ Tesseract not found. Arabic PDF extraction will likely fail.")
26
+
27
+ def extract_text_from_file(file_path):
28
+ ext = os.path.splitext(file_path)[1].lower()
29
+
30
+ try:
31
+ if ext == ".pdf":
32
+ with pdfplumber.open(file_path) as pdf:
33
+ extracted = "\n".join(page.extract_text() for page in pdf.pages if page.extract_text())
34
+
35
+ sample = extracted[:1000].strip()
36
+ if sample:
37
+ try:
38
+ lang = detect(sample)
39
+ except Exception:
40
+ lang = "unknown"
41
+
42
+ if lang == "ar":
43
+ print("πŸ“„ Using Arabic-aware extractor for PDF.")
44
+ try:
45
+ arabic_doc = Document(document_path=file_path, language="ara")
46
+ pdf2text = PDF2Text(document=arabic_doc)
47
+ extracted = pdf2text.extract()
48
+ if isinstance(extracted, list):
49
+ if isinstance(extracted[0], dict):
50
+ return "\n".join([item.get("text", "") for item in extracted])
51
+ elif isinstance(extracted[0], str):
52
+ return "\n".join(extracted)
53
+ elif isinstance(extracted, str):
54
+ return extracted
55
+ else:
56
+ return "[Error: Unexpected format in extracted text.]"
57
+ except Exception as e:
58
+ print(f"❌ Arabic PDF extraction failed: {e}")
59
+ return "[Error: Failed to extract Arabic text from PDF.]"
60
+ else:
61
+ return extracted
62
+ else:
63
+ arabic_doc = Document(document_path=file_path, language="ara")
64
+ pdf2text = PDF2Text(document=arabic_doc)
65
+ extracted = pdf2text.extract()
66
+ if isinstance(extracted, list):
67
+ if isinstance(extracted[0], dict):
68
+ return "\n".join([item.get("text", "") for item in extracted])
69
+ elif isinstance(extracted[0], str):
70
+ return "\n".join(extracted)
71
+ elif isinstance(extracted, str):
72
+ return extracted
73
+ else:
74
+ return "[Error: Unexpected format in extracted text.]"
75
+
76
+ elif ext == ".docx":
77
+ return docx2txt.process(file_path)
78
+
79
+ elif ext == ".txt":
80
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
81
+ return f.read()
82
+
83
+ else:
84
+ return "[Unsupported file format]"
85
+
86
+ except Exception as e:
87
+ return f"[Error reading file: {e}]"
88
+
89
+
90
+ def send_to_flowise(file, country, language):
91
+ if file is None or not country or not language:
92
+ return "❗Please upload a contract, select a country and language."
93
+
94
+ try:
95
+ contract_text = extract_text_from_file(file.name)
96
+ if not contract_text.strip():
97
+ return "⚠️ Could not read any content from the uploaded file."
98
+
99
+ prompt = f"""Please audit the following employment contract in light of {country} labor law.
100
+ Only refer to the provided law document (do not use external knowledge).
101
+ Is the contract compliant? Provide reasoning and highlight any issues, and suggest improvements.
102
+ Be precise and don't miss any details in the contract.
103
+ Please respond in {language}.
104
+ <CONTRACT START>
105
+ {contract_text}
106
+ <CONTRACT END>
107
+ """
108
+
109
+ payload = {
110
+ "question": prompt,
111
+ "chatId": str(uuid.uuid4())
112
+ }
113
+
114
+ res = requests.post(FLOWISE_URL, json=payload, timeout=300)
115
+ print("πŸ” Flowise raw response:", res.text)
116
+
117
+ if res.status_code != 200:
118
+ return f"❌ Flowise error {res.status_code}: {res.text}"
119
+
120
+ return res.json().get("text", "⚠️ Flowise returned no text.")
121
+
122
+ except Exception as e:
123
+ return f"❌ Connection error: {e}"
124
+
125
+ with gr.Blocks(title="Contract Auditor") as demo:
126
+ gr.Markdown("## πŸ“‘ Contract Auditor")
127
+
128
+ with gr.Row():
129
+ country_dropdown = gr.Dropdown(choices=COUNTRIES, label="🌍 Select Country", interactive=True)
130
+ language_dropdown = gr.Dropdown(choices=LANGUAGES, label="πŸ—£οΈ Response Language", interactive=True)
131
+ file_input = gr.File(label="πŸ“Ž Upload a contract file", file_types=[".pdf", ".docx", ".txt"], type="filepath")
132
+
133
+ submit_btn = gr.Button("πŸ“€ Audit Contract")
134
+ output = gr.Textbox(label="🧠 Audit Result", lines=12)
135
+
136
+ submit_btn.click(fn=send_to_flowise, inputs=[file_input, country_dropdown, language_dropdown], outputs=output)
137
+
138
+ demo.launch()