TanujInsane commited on
Commit
0c5c2e4
ยท
verified ยท
1 Parent(s): 6d78f68

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -23
app.py CHANGED
@@ -76,8 +76,12 @@ def api_agent_classify():
76
  priority = agent.get_priority(text)
77
  return jsonify({"category": category, "priority": priority, "scores": scores})
78
 
 
 
 
 
79
  def run_flask():
80
- api.run(host="0.0.0.0", port=7861, debug=False)
81
 
82
  env_state = {"env": None, "difficulty": "easy"}
83
 
@@ -90,13 +94,15 @@ def create_env(difficulty):
90
  cats = CATEGORIES[difficulty]
91
  proba = model.predict_proba([obs["content"]])[0]
92
  top3 = sorted(enumerate(proba), key=lambda x: -x[1])[:3]
93
- explain = "\n".join([f" {cats[i] if i < len(cats) else f'Cat_{i}'}: {p*100:.1f}%" for i,p in top3])
94
  pred_idx = int(model.predict([obs["content"]])[0])
95
  pred_cat = cats[pred_idx] if pred_idx < len(cats) else f"Cat_{pred_idx}"
96
- return (f"โœ… Environment created! Difficulty: {difficulty}",
97
- obs["content"],
98
- f"๐Ÿค– Model predicts: **{pred_cat}**\n\nTop 3 predictions:\n{explain}",
99
- "")
 
 
100
 
101
  def classify_doc(category_idx):
102
  e = env_state["env"]
@@ -113,12 +119,15 @@ def classify_doc(category_idx):
113
  cats = CATEGORIES[difficulty]
114
  proba = model.predict_proba([obs["content"]])[0]
115
  top3 = sorted(enumerate(proba), key=lambda x: -x[1])[:3]
116
- explain = "\n".join([f" {cats[i] if i < len(cats) else f'Cat_{i}'}: {p*100:.1f}%" for i,p in top3])
117
  pred_idx = int(model.predict([obs["content"]])[0])
118
  pred_cat = cats[pred_idx] if pred_idx < len(cats) else f"Cat_{pred_idx}"
119
- return (result, obs["content"],
120
- f"๐Ÿค– Model predicts: **{pred_cat}**\n\nTop 3 predictions:\n{explain}",
121
- str(info))
 
 
 
122
 
123
  def run_baseline_all():
124
  rows = []
@@ -132,11 +141,11 @@ def process_ticket_ui(ticket_text, difficulty):
132
  return "โŒ Please enter ticket text!", "", "", "", "", ""
133
  result = agent.process_ticket(ticket_text, difficulty=difficulty)
134
  category_out = f"๐Ÿท๏ธ {result['category']} (confidence: {result['confidence']*100:.1f}%)"
135
- priority_out = f"๐Ÿšจ {result['priority'].upper()}"
136
- dept_out = f"๐Ÿข {result['department']}\n๐Ÿ“ง {result['email']}\nโฑ๏ธ SLA: {result['sla']}"
137
- top3_out = "\n".join([f" {c}: {p*100:.1f}%" for c,p in result['top3']])
138
- ref_out = f"๐ŸŽซ {result['ref_id']} | โฐ {result['timestamp'][:19]}"
139
- reply_out = result['reply']
140
  return category_out, priority_out, dept_out, top3_out, ref_out, reply_out
141
 
142
  SAMPLE_TICKETS = {
@@ -168,7 +177,7 @@ with gr.Blocks(title="Document Classification OpenEnv") as demo:
168
  lines=6,
169
  placeholder="Paste email, chat message, bug report, HR query..."
170
  )
171
- diff_agent = gr.Radio(["easy","medium","hard"], value="medium", label="Model Difficulty")
172
  btn_process = gr.Button("๐Ÿš€ Process Ticket", variant="primary")
173
  with gr.Column(scale=2):
174
  ref_out_box = gr.Textbox(label="๐ŸŽซ Reference ID & Timestamp")
@@ -186,7 +195,7 @@ with gr.Blocks(title="Document Classification OpenEnv") as demo:
186
  )
187
 
188
  with gr.Tab("๐ŸŽฎ Interactive Demo"):
189
- diff = gr.Radio(["easy","medium","hard"], value="easy", label="Difficulty")
190
  btn_create = gr.Button("Create Environment", variant="primary")
191
  status = gr.Textbox(label="Status")
192
  with gr.Row():
@@ -202,7 +211,7 @@ with gr.Blocks(title="Document Classification OpenEnv") as demo:
202
  with gr.Tab("๐Ÿ“Š Baseline Evaluation"):
203
  gr.Markdown("TF-IDF + Logistic Regression baseline โ€” models pre-trained at startup for instant results.")
204
  btn_eval = gr.Button("Run All Tasks", variant="primary")
205
- score_table = gr.Dataframe(headers=["Task","Score","Accuracy","Time"], label="Results")
206
  btn_eval.click(run_baseline_all, outputs=score_table)
207
 
208
  with gr.Tab("๐Ÿ“‹ Environment Info"):
@@ -220,13 +229,15 @@ with gr.Blocks(title="Document Classification OpenEnv") as demo:
220
  `Ticket Input` โ†’ `ML Classify` โ†’ `Rule Priority` โ†’ `Department Route` โ†’ `Auto Reply`
221
 
222
  ## API Endpoints (port 7861)
223
- - `POST /api/reset` โ€” `{"difficulty": "easy", "seed": 42}`
224
- - `POST /api/step` โ€” `{"action": 0}`
225
- - `POST /api/agent/process` โ€” `{"text": "my invoice is wrong", "difficulty": "medium"}`
226
- - `POST /api/agent/classify` โ€” `{"text": "urgent bug", "difficulty": "easy"}`
 
 
227
  """)
228
 
229
  if __name__ == "__main__":
230
  t = threading.Thread(target=run_flask, daemon=True)
231
  t.start()
232
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
76
  priority = agent.get_priority(text)
77
  return jsonify({"category": category, "priority": priority, "scores": scores})
78
 
79
+ @api.route("/health", methods=["GET"])
80
+ def health():
81
+ return jsonify({"status": "ok", "models_loaded": list(models.keys())})
82
+
83
  def run_flask():
84
+ api.run(host="0.0.0.0", port=7861, debug=False, use_reloader=False, threaded=True)
85
 
86
  env_state = {"env": None, "difficulty": "easy"}
87
 
 
94
  cats = CATEGORIES[difficulty]
95
  proba = model.predict_proba([obs["content"]])[0]
96
  top3 = sorted(enumerate(proba), key=lambda x: -x[1])[:3]
97
+ explain = "\n".join([f" {cats[i] if i < len(cats) else f'Cat_{i}'}: {p*100:.1f}%" for i, p in top3])
98
  pred_idx = int(model.predict([obs["content"]])[0])
99
  pred_cat = cats[pred_idx] if pred_idx < len(cats) else f"Cat_{pred_idx}"
100
+ return (
101
+ f"โœ… Environment created! Difficulty: {difficulty}",
102
+ obs["content"],
103
+ f"๐Ÿค– Model predicts: **{pred_cat}**\n\nTop 3 predictions:\n{explain}",
104
+ ""
105
+ )
106
 
107
  def classify_doc(category_idx):
108
  e = env_state["env"]
 
119
  cats = CATEGORIES[difficulty]
120
  proba = model.predict_proba([obs["content"]])[0]
121
  top3 = sorted(enumerate(proba), key=lambda x: -x[1])[:3]
122
+ explain = "\n".join([f" {cats[i] if i < len(cats) else f'Cat_{i}'}: {p*100:.1f}%" for i, p in top3])
123
  pred_idx = int(model.predict([obs["content"]])[0])
124
  pred_cat = cats[pred_idx] if pred_idx < len(cats) else f"Cat_{pred_idx}"
125
+ return (
126
+ result,
127
+ obs["content"],
128
+ f"๐Ÿค– Model predicts: **{pred_cat}**\n\nTop 3 predictions:\n{explain}",
129
+ str(info)
130
+ )
131
 
132
  def run_baseline_all():
133
  rows = []
 
141
  return "โŒ Please enter ticket text!", "", "", "", "", ""
142
  result = agent.process_ticket(ticket_text, difficulty=difficulty)
143
  category_out = f"๐Ÿท๏ธ {result['category']} (confidence: {result['confidence']*100:.1f}%)"
144
+ priority_out = f"๐Ÿšจ {result['priority'].upper()}"
145
+ dept_out = f"๐Ÿข {result['department']}\n๐Ÿ“ง {result['email']}\nโฑ๏ธ SLA: {result['sla']}"
146
+ top3_out = "\n".join([f" {c}: {p*100:.1f}%" for c, p in result['top3']])
147
+ ref_out = f"๐ŸŽซ {result['ref_id']} | โฐ {result['timestamp'][:19]}"
148
+ reply_out = result['reply']
149
  return category_out, priority_out, dept_out, top3_out, ref_out, reply_out
150
 
151
  SAMPLE_TICKETS = {
 
177
  lines=6,
178
  placeholder="Paste email, chat message, bug report, HR query..."
179
  )
180
+ diff_agent = gr.Radio(["easy", "medium", "hard"], value="medium", label="Model Difficulty")
181
  btn_process = gr.Button("๐Ÿš€ Process Ticket", variant="primary")
182
  with gr.Column(scale=2):
183
  ref_out_box = gr.Textbox(label="๐ŸŽซ Reference ID & Timestamp")
 
195
  )
196
 
197
  with gr.Tab("๐ŸŽฎ Interactive Demo"):
198
+ diff = gr.Radio(["easy", "medium", "hard"], value="easy", label="Difficulty")
199
  btn_create = gr.Button("Create Environment", variant="primary")
200
  status = gr.Textbox(label="Status")
201
  with gr.Row():
 
211
  with gr.Tab("๐Ÿ“Š Baseline Evaluation"):
212
  gr.Markdown("TF-IDF + Logistic Regression baseline โ€” models pre-trained at startup for instant results.")
213
  btn_eval = gr.Button("Run All Tasks", variant="primary")
214
+ score_table = gr.Dataframe(headers=["Task", "Score", "Accuracy", "Time"], label="Results")
215
  btn_eval.click(run_baseline_all, outputs=score_table)
216
 
217
  with gr.Tab("๐Ÿ“‹ Environment Info"):
 
229
  `Ticket Input` โ†’ `ML Classify` โ†’ `Rule Priority` โ†’ `Department Route` โ†’ `Auto Reply`
230
 
231
  ## API Endpoints (port 7861)
232
+ - `GET /health`
233
+ - `POST /api/reset`
234
+ - `POST /api/step`
235
+ - `POST /api/run`
236
+ - `POST /api/agent/process`
237
+ - `POST /api/agent/classify`
238
  """)
239
 
240
  if __name__ == "__main__":
241
  t = threading.Thread(target=run_flask, daemon=True)
242
  t.start()
243
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=True)