vachaspathi commited on
Commit
a1a3598
Β·
verified Β·
1 Parent(s): 261039b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -45
app.py CHANGED
@@ -2,87 +2,135 @@ import gradio as gr
2
  import ai_engine
3
  import zoho_client
4
  import time
 
5
  import sys
6
 
7
  # Force unbuffered output for logs
8
  sys.stdout.reconfigure(line_buffering=True)
9
 
10
- def process_pipeline(file):
11
- print("--- NEW REQUEST STARTED ---")
12
- logs = ""
 
 
 
 
 
 
13
 
 
 
 
 
14
  # 1. OCR
15
  try:
16
- print("Step 1: Starting OCR...")
17
  logs += "πŸ‘οΈ Scanning Document (OCR)...\n"
18
- yield None, logs
19
-
20
  text, img, meta = ai_engine.perform_ocr(file)
21
 
22
  if not text:
23
- print("Error: OCR returned empty text.")
24
- logs += "❌ OCR Failed. No text found in document.\n"
25
- yield None, logs
26
  return
27
- print(f"OCR Success. Text length: {len(text)}")
28
-
29
  except Exception as e:
30
- print(f"OCR Exception: {e}")
31
- logs += f"❌ System Error during OCR: {e}\n"
32
- yield None, logs
33
  return
34
 
35
  # 2. AI Extraction
36
  try:
37
- print("Step 2: Running AI Extraction...")
38
- logs += "🧠 AI Analyzing & Classifying (this takes ~10s)...\n"
39
- yield img, logs
40
 
41
  ai_output = ai_engine.extract_intelligent_json(text, meta)
42
- print(f"AI Output: {ai_output}")
43
 
44
  doc_type = ai_output.get('doc_type', 'unknown')
45
- logs += f"πŸ€– Detected: {doc_type.upper()}\n"
46
- logs += "----------------------------------\n"
47
- yield img, logs
 
 
 
 
48
 
49
  except Exception as e:
50
- print(f"AI Exception: {e}")
51
- logs += f"❌ AI Analysis Failed: {e}\n"
52
- yield img, logs
53
- return
 
 
 
 
 
 
 
 
54
 
55
- # 3. Orchestration
56
- print("Step 3: Starting Zoho Orchestration...")
 
 
 
 
 
 
 
 
 
 
57
  try:
58
  # Consume the generator from zoho_client
59
  for update in zoho_client.route_and_execute(ai_output):
60
- print(f"Zoho Update: {update.strip()}")
61
  logs += update
62
- yield img, logs
63
- time.sleep(0.1) # Prevent UI flooding
64
 
65
  except Exception as e:
66
- print(f"Orchestrator Exception: {e}")
67
  logs += f"\n❌ Orchestrator Error: {e}"
68
- yield img, logs
69
 
70
- # --- UI SETUP ---
71
- with gr.Blocks(title="Zoho Agentic") as demo:
72
- gr.Markdown("## ⚑ Zoho Agentic Orchestrator (Debug Mode)")
73
- gr.Markdown("If the UI hangs, check the 'Logs' tab in the Hugging Face Space.")
 
 
74
 
75
  with gr.Row():
76
- f_in = gr.File(label="Upload Document")
77
- btn = gr.Button("Start Processing", variant="primary")
78
-
79
- with gr.Row():
80
- out_img = gr.Image(label="Document View", height=400)
81
- out_log = gr.Code(label="Live Execution Logs", language="shell")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- btn.click(process_pipeline, f_in, [out_img, out_log])
 
 
 
 
 
84
 
85
  if __name__ == "__main__":
86
- # CRITICAL FIX: ssr_mode=False prevents blank screens on some browsers
87
- print("Launching Gradio Server...")
88
  demo.launch(ssr_mode=False)
 
2
  import ai_engine
3
  import zoho_client
4
  import time
5
+ import json
6
  import sys
7
 
8
  # Force unbuffered output for logs
9
  sys.stdout.reconfigure(line_buffering=True)
10
 
11
+ # ==========================================
12
+ # 1. STEP 1: ANALYZE (OCR + AI)
13
+ # ==========================================
14
+ def step_analyze(file):
15
+ """
16
+ Runs OCR and AI extraction, but DOES NOT send to Zoho.
17
+ Returns the data for the user to edit.
18
+ """
19
+ logs = "--- PHASE 1: ANALYSIS ---\n"
20
 
21
+ if file is None:
22
+ yield None, None, "❌ Please upload a file first."
23
+ return
24
+
25
  # 1. OCR
26
  try:
 
27
  logs += "πŸ‘οΈ Scanning Document (OCR)...\n"
28
+ yield None, None, logs
 
29
  text, img, meta = ai_engine.perform_ocr(file)
30
 
31
  if not text:
32
+ logs += "❌ OCR Failed. No text found.\n"
33
+ yield None, None, logs
 
34
  return
 
 
35
  except Exception as e:
36
+ logs += f"❌ OCR Error: {e}\n"
37
+ yield None, None, logs
 
38
  return
39
 
40
  # 2. AI Extraction
41
  try:
42
+ logs += "🧠 AI Analyzing & Classifying (1.5B Model)...\n"
43
+ yield img, None, logs
 
44
 
45
  ai_output = ai_engine.extract_intelligent_json(text, meta)
 
46
 
47
  doc_type = ai_output.get('doc_type', 'unknown')
48
+ logs += f"πŸ€– Detected Type: {doc_type.upper()}\n"
49
+ logs += "βœ… Analysis Complete. Please REVIEW the JSON below before syncing.\n"
50
+
51
+ # Return Image, JSON Data for Editor, and Logs
52
+ # We dump to string for the Code editor, nicely formatted
53
+ json_str = json.dumps(ai_output, indent=4)
54
+ yield img, json_str, logs
55
 
56
  except Exception as e:
57
+ logs += f"❌ AI Error: {e}\n"
58
+ yield img, None, logs
59
+
60
+ # ==========================================
61
+ # 2. STEP 2: SYNC (Zoho Push)
62
+ # ==========================================
63
+ def step_sync(json_data_str):
64
+ """
65
+ Takes the EDITED JSON from the UI and pushes it to Zoho.
66
+ """
67
+ logs = "\n--- PHASE 2: ZOHO SYNC ---\n"
68
+ yield logs
69
 
70
+ # 1. Parse Edited JSON
71
+ try:
72
+ if not json_data_str:
73
+ yield logs + "❌ Error: No data to sync. Please analyze a document first."
74
+ return
75
+
76
+ ai_output = json.loads(json_data_str)
77
+ except Exception as e:
78
+ yield logs + f"❌ Invalid JSON Format: {e}\n(Did you delete a comma or bracket?)"
79
+ return
80
+
81
+ # 2. Execute Zoho Logic
82
  try:
83
  # Consume the generator from zoho_client
84
  for update in zoho_client.route_and_execute(ai_output):
 
85
  logs += update
86
+ yield logs
87
+ time.sleep(0.1) # Visual flow
88
 
89
  except Exception as e:
 
90
  logs += f"\n❌ Orchestrator Error: {e}"
91
+ yield logs
92
 
93
+ # ==========================================
94
+ # 3. UI LAYOUT (Human-in-the-Loop)
95
+ # ==========================================
96
+ with gr.Blocks(title="Zoho Agentic HITL", theme=gr.themes.Soft()) as demo:
97
+ gr.Markdown("## πŸ•΅οΈβ€β™‚οΈ Zoho Agent: Human-in-the-Loop")
98
+ gr.Markdown("1. **Upload** & Analyze. 2. **Review/Edit** the extracted data. 3. **Confirm** to Sync.")
99
 
100
  with gr.Row():
101
+ # LEFT COLUMN: Input & Visuals
102
+ with gr.Column(scale=1):
103
+ f_in = gr.File(label="1. Upload Document")
104
+ btn_analyze = gr.Button("πŸ” Analyze Document", variant="secondary")
105
+ out_img = gr.Image(label="Document Preview", height=500)
106
+
107
+ # RIGHT COLUMN: Data Editor & logs
108
+ with gr.Column(scale=1):
109
+ # The Editor
110
+ gr.Markdown("### 2. Review Extracted Data")
111
+ json_editor = gr.Code(label="JSON Editor (Editable)", language="json", interactive=True, lines=20)
112
+
113
+ # The Action
114
+ btn_sync = gr.Button("πŸš€ Confirm & Sync to Zoho", variant="primary")
115
+
116
+ # The Logs
117
+ out_log = gr.Code(label="Execution Logs", language="shell", lines=10)
118
+
119
+ # --- EVENT WIRING ---
120
+
121
+ # Click Analyze -> Updates Image, JSON Editor, Logs
122
+ btn_analyze.click(
123
+ fn=step_analyze,
124
+ inputs=[f_in],
125
+ outputs=[out_img, json_editor, out_log]
126
+ )
127
 
128
+ # Click Sync -> Reads JSON Editor -> Updates Logs
129
+ btn_sync.click(
130
+ fn=step_sync,
131
+ inputs=[json_editor],
132
+ outputs=[out_log]
133
+ )
134
 
135
  if __name__ == "__main__":
 
 
136
  demo.launch(ssr_mode=False)