Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,237 +1,59 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
"AMAZON WEB SERVICES": {"id": "VEN-001", "status": "Active", "currency": "INR"},
|
| 26 |
-
"ZOHO CORPORATION": {"id": "VEN-002", "status": "Active", "currency": "INR"},
|
| 27 |
-
"MICROSOFT AZURE": {"id": "VEN-003", "status": "Active", "currency": "INR"}
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
# ==========================================
|
| 31 |
-
# 2. SYSTEM UTILITIES (The "Hands")
|
| 32 |
-
# ==========================================
|
| 33 |
-
|
| 34 |
-
def mock_email_admin(subject, body):
|
| 35 |
-
"""SOP C.3: Email Admin on Failure"""
|
| 36 |
-
log_entry = f"""
|
| 37 |
-
[MOCK EMAIL SERVER]
|
| 38 |
-
TO: {ADMIN_EMAIL}
|
| 39 |
-
SUBJECT: {subject}
|
| 40 |
-
BODY: {body}
|
| 41 |
-
------------------------------------------------
|
| 42 |
-
"""
|
| 43 |
-
print(log_entry)
|
| 44 |
-
return "📧 Alert Sent to Admin"
|
| 45 |
-
|
| 46 |
-
def perform_ocr_with_confidence(file_obj):
|
| 47 |
-
"""
|
| 48 |
-
Runs OCR and calculates a heuristic confidence score.
|
| 49 |
-
Since Tesseract raw confidence is tricky, we use text density/clarity as a proxy for this demo.
|
| 50 |
-
"""
|
| 51 |
-
if file_obj is None: return None, 0.0, "No File"
|
| 52 |
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
images = convert_from_path(file_obj, first_page=1, last_page=1)
|
| 57 |
-
image = images[0]
|
| 58 |
-
else:
|
| 59 |
-
image = Image.open(file_obj).convert("RGB")
|
| 60 |
-
|
| 61 |
-
text = pytesseract.image_to_string(image)
|
| 62 |
|
| 63 |
-
#
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
score = 0.70 # Low confidence
|
| 72 |
else:
|
| 73 |
-
|
| 74 |
|
| 75 |
-
return image, score, text
|
| 76 |
except Exception as e:
|
| 77 |
-
return
|
| 78 |
-
|
| 79 |
-
def normalize_date(extracted_date):
|
| 80 |
-
"""SOP B.1: Force Today's Date if missing."""
|
| 81 |
-
if extracted_date and "null" not in extracted_date.lower():
|
| 82 |
-
return extracted_date
|
| 83 |
-
return datetime.datetime.now().strftime("%Y-%m-%d") + " (Auto-Filled)"
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
if key in VENDOR_DB:
|
| 94 |
-
return VENDOR_DB[key]["id"], "Active"
|
| 95 |
-
else:
|
| 96 |
-
# SOP A.2.b: Create new and flag
|
| 97 |
-
new_id = f"VEN-{random.randint(1000, 9999)}"
|
| 98 |
-
VENDOR_DB[key] = {"id": new_id, "status": "Pending_Review", "currency": "INR"}
|
| 99 |
-
return new_id, "Created (Pending Review)"
|
| 100 |
-
|
| 101 |
-
# ==========================================
|
| 102 |
-
# 3. AI BRAIN (Qwen Loading)
|
| 103 |
-
# ==========================================
|
| 104 |
-
print(f">>> SYSTEM: Initializing {MODEL_ID}...")
|
| 105 |
-
try:
|
| 106 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 107 |
-
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="cpu", torch_dtype=torch.float32, low_cpu_mem_usage=True)
|
| 108 |
-
print(">>> SYSTEM: AI Online.")
|
| 109 |
-
except Exception as e:
|
| 110 |
-
print(f"CRITICAL: {e}")
|
| 111 |
-
model = None
|
| 112 |
-
|
| 113 |
-
# ==========================================
|
| 114 |
-
# 4. PROMPTING STRATEGY (SOPs & Guardrails)
|
| 115 |
-
# ==========================================
|
| 116 |
-
SYSTEM_PROMPT = """
|
| 117 |
-
<|im_start|>system
|
| 118 |
-
You are an **Invoice Assistant** strictly following these SOPs:
|
| 119 |
-
1. **Source of Truth:** The Invoice text is the absolute authority for amounts and dates.
|
| 120 |
-
2. **Extraction:** Extract 'Vendor', 'Date', 'Total', and 'Tax'. If missing, output 'null'.
|
| 121 |
-
3. **Currency:** Always assume INR (Indian Rupee) for now.
|
| 122 |
-
4. **Output:** Only raw JSON or bullet points. No chit-chat.
|
| 123 |
-
<|im_end|>
|
| 124 |
-
"""
|
| 125 |
-
|
| 126 |
-
def query_llm(prompt, history=[]):
|
| 127 |
-
if model is None: return "System Error: AI Offline"
|
| 128 |
-
|
| 129 |
-
full_text = f"{SYSTEM_PROMPT}"
|
| 130 |
-
for u, a in history:
|
| 131 |
-
full_text += f"<|im_start|>user\n{u}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>\n"
|
| 132 |
-
full_text += f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
|
| 133 |
-
|
| 134 |
-
inputs = tokenizer(full_text, return_tensors="pt")
|
| 135 |
-
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 136 |
-
|
| 137 |
-
thread = Thread(target=model.generate, kwargs=dict(inputs, streamer=streamer, max_new_tokens=256, temperature=0.3))
|
| 138 |
-
thread.start()
|
| 139 |
-
|
| 140 |
-
response = ""
|
| 141 |
-
for t in streamer: response += t
|
| 142 |
-
return response
|
| 143 |
-
|
| 144 |
-
# ==========================================
|
| 145 |
-
# 5. THE ORCHESTRATOR (Main Logic Flow)
|
| 146 |
-
# ==========================================
|
| 147 |
-
def orchestrate_process(file_obj):
|
| 148 |
-
logs = "🔵 Process Started...\n"
|
| 149 |
-
|
| 150 |
-
# Step 1: OCR
|
| 151 |
-
img, score, text = perform_ocr_with_confidence(file_obj)
|
| 152 |
-
logs += f"👁️ OCR Completed. Confidence Score: {score}\n"
|
| 153 |
-
|
| 154 |
-
# Step 2: Confidence Check (SOP A.1)
|
| 155 |
-
workflow_status = "APPROVED"
|
| 156 |
-
if score < CONFIDENCE_THRESHOLD:
|
| 157 |
-
workflow_status = "NEEDS_REVIEW"
|
| 158 |
-
logs += f"⚠️ Low Confidence (<{CONFIDENCE_THRESHOLD}). Workflow flagged for Manual Review.\n"
|
| 159 |
-
|
| 160 |
-
# Step 3: AI Extraction
|
| 161 |
-
extraction_prompt = f"""
|
| 162 |
-
Extract the following fields from this invoice text. Return valid JSON only.
|
| 163 |
-
Fields: vendor_name, invoice_date (YYYY-MM-DD), total_amount, line_items_summary.
|
| 164 |
-
|
| 165 |
-
INVOICE TEXT:
|
| 166 |
-
{text[:2000]}
|
| 167 |
-
"""
|
| 168 |
-
ai_json_str = query_llm(extraction_prompt)
|
| 169 |
-
|
| 170 |
-
# Attempt to parse AI JSON (Simple fallback parsing)
|
| 171 |
-
try:
|
| 172 |
-
# Cleanup markdown code blocks if AI adds them
|
| 173 |
-
clean_json = ai_json_str.replace("```json", "").replace("```", "").strip()
|
| 174 |
-
data = json.loads(clean_json)
|
| 175 |
-
except:
|
| 176 |
-
data = {"vendor_name": "null", "invoice_date": "null", "total_amount": "0"}
|
| 177 |
-
logs += "⚠️ AI JSON Parsing Failed. Using raw fallbacks.\n"
|
| 178 |
-
|
| 179 |
-
# Step 4: Data Normalization (SOP B.1 & A.2)
|
| 180 |
-
final_date = normalize_date(data.get("invoice_date"))
|
| 181 |
-
vendor_id, vendor_status = manage_vendor(data.get("vendor_name"))
|
| 182 |
-
|
| 183 |
-
if vendor_status == "Created (Pending Review)":
|
| 184 |
-
logs += f"🆕 New Vendor Detected: {data.get('vendor_name')}. Created ID: {vendor_id}\n"
|
| 185 |
-
|
| 186 |
-
# Step 5: Zoho Payload Construction (SOP A.3)
|
| 187 |
-
zoho_payload = {
|
| 188 |
-
"customer_id": vendor_id,
|
| 189 |
-
"date": final_date,
|
| 190 |
-
"line_items": [
|
| 191 |
-
{
|
| 192 |
-
"name": data.get("line_items_summary", "Services Rendered"),
|
| 193 |
-
"rate": data.get("total_amount", 0),
|
| 194 |
-
"quantity": 1
|
| 195 |
-
}
|
| 196 |
-
],
|
| 197 |
-
"currency_id": "INR", # SOP A.5
|
| 198 |
-
"status": "draft" if workflow_status == "NEEDS_REVIEW" else "sent"
|
| 199 |
-
}
|
| 200 |
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
try:
|
| 204 |
-
total_val = float(str(data.get("total_amount", "0")).replace(",",""))
|
| 205 |
-
if total_val > 1000000:
|
| 206 |
-
raise Exception("Simulated Zoho API Timeout")
|
| 207 |
-
except Exception as e:
|
| 208 |
-
alert_msg = mock_email_admin("Zoho Sync Failed", str(e))
|
| 209 |
-
logs += f"❌ {alert_msg}\n"
|
| 210 |
-
|
| 211 |
-
return img, json.dumps(zoho_payload, indent=2), logs, workflow_status
|
| 212 |
-
|
| 213 |
-
# ==========================================
|
| 214 |
-
# 6. UI LAUNCHER
|
| 215 |
-
# ==========================================
|
| 216 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="Zoho Invoice Orchestrator") as demo:
|
| 217 |
-
gr.Markdown("## 🧠 Zoho Invoice Orchestrator (SOP Compliant)")
|
| 218 |
|
| 219 |
-
|
| 220 |
-
with gr.Column():
|
| 221 |
-
file_in = gr.File(label="Upload Invoice")
|
| 222 |
-
process_btn = gr.Button("🚀 Process Invoice", variant="primary")
|
| 223 |
-
img_out = gr.Image(label="OCR Preview", height=300)
|
| 224 |
-
|
| 225 |
-
with gr.Column():
|
| 226 |
-
status_box = gr.Textbox(label="Workflow Status (SOP A.1)")
|
| 227 |
-
log_box = gr.Textbox(label="Orchestrator Logs", lines=6)
|
| 228 |
-
json_out = gr.JSON(label="Zoho V3 Payload")
|
| 229 |
-
|
| 230 |
-
process_btn.click(
|
| 231 |
-
fn=orchestrate_process,
|
| 232 |
-
inputs=[file_in],
|
| 233 |
-
outputs=[img_out, json_out, log_box, status_box]
|
| 234 |
-
)
|
| 235 |
|
| 236 |
if __name__ == "__main__":
|
| 237 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
|
| 4 |
+
# --- YOUR CREDENTIALS (HARDCODED FOR SPEED) ---
|
| 5 |
+
CLIENT_ID = "1000.SIMKGAO5719K0TQ0QZQ31ZU57RLFNQ"
|
| 6 |
+
CLIENT_SECRET = "60b329b4fe51930abee900cba6524ec7332cd67e06"
|
| 7 |
+
# IMPORTANT: This must match EXACTLY what you set in Zoho Console
|
| 8 |
+
# If you used "http://www.google.com" in console, keep it here.
|
| 9 |
+
REDIRECT_URI = "http://www.google.com"
|
| 10 |
+
|
| 11 |
+
def get_zoho_token(auth_code, region):
|
| 12 |
+
"""Exchanges the 10-min code for a permanent Refresh Token"""
|
| 13 |
+
|
| 14 |
+
# Select Data Center (India accounts use .in, US/Global use .com)
|
| 15 |
+
domain = "zoho.in" if region == "India (.in)" else "zoho.com"
|
| 16 |
+
url = f"https://accounts.{domain}/oauth/v2/token"
|
| 17 |
+
|
| 18 |
+
payload = {
|
| 19 |
+
"code": auth_code,
|
| 20 |
+
"client_id": CLIENT_ID,
|
| 21 |
+
"client_secret": CLIENT_SECRET,
|
| 22 |
+
"redirect_uri": REDIRECT_URI,
|
| 23 |
+
"grant_type": "authorization_code"
|
| 24 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
try:
|
| 27 |
+
print(f"Attempting connection to {url}...")
|
| 28 |
+
response = requests.post(url, data=payload)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
# Check for success
|
| 31 |
+
if response.status_code == 200 and "refresh_token" in response.text:
|
| 32 |
+
data = response.json()
|
| 33 |
+
return (
|
| 34 |
+
f"✅ SUCCESS! \n\nREFRESH TOKEN:\n{data['refresh_token']}\n\n"
|
| 35 |
+
f"ACCESS TOKEN:\n{data['access_token']}\n\n"
|
| 36 |
+
"👉 Save the 'Refresh Token' securely. It never expires."
|
| 37 |
+
)
|
|
|
|
| 38 |
else:
|
| 39 |
+
return f"❌ FAILED:\n{response.text}\n\nHint: Did you generate a NEW code? The old one expires in 10 mins."
|
| 40 |
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
+
return f"System Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
# --- UI ---
|
| 45 |
+
with gr.Blocks(title="Zoho Token Generator") as demo:
|
| 46 |
+
gr.Markdown("## 🔑 Zoho Token Generator")
|
| 47 |
+
gr.Markdown("1. Go to Zoho Console -> Self Client -> Generate Code.\n2. Paste the code below immediately.")
|
| 48 |
|
| 49 |
+
with gr.Row():
|
| 50 |
+
code_input = gr.Textbox(label="Paste New Authorization Code (1000.xxxx...)", placeholder="1000.726...")
|
| 51 |
+
region_input = gr.Radio(["India (.in)", "Global (.com)"], label="Zoho Account Region", value="India (.in)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
btn = gr.Button("Generate Permanent Token", variant="primary")
|
| 54 |
+
output = gr.Textbox(label="Result (Copy this)", lines=10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
btn.click(get_zoho_token, inputs=[code_input, region_input], outputs=output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
if __name__ == "__main__":
|
| 59 |
demo.launch()
|