TanujInsane commited on
Commit
2c2c2cc
·
1 Parent(s): f8ffb6d

upgrade gradio 6.x - professional dark UI

Browse files
Files changed (2) hide show
  1. app.py +92 -157
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,9 +1,10 @@
1
- import gradio as gr
2
  import json
3
  import time
4
  from environment import DocumentClassificationEnv
5
  from tasks import TaskDataGenerator
6
 
 
7
  def predict_category(obs, difficulty):
8
  gen = TaskDataGenerator(difficulty, seed=42)
9
  tc = obs.get("true_category", "") if isinstance(obs, dict) else ""
@@ -12,142 +13,82 @@ def predict_category(obs, difficulty):
12
  except (ValueError, AttributeError):
13
  return 0
14
 
 
15
  SAMPLE_TICKETS = {
16
- "Billing Issue": "I was overcharged on my last invoice. The amount shows $150 but it should be $100.",
17
- "Urgent Bug": "CRITICAL: Our production server is completely down! All users are affected. Need immediate help!",
18
- "Feature Request": "I would like to request a new feature to export reports in PDF format.",
19
- "HR Complaint": "I need to file a formal complaint about workplace harassment by my manager.",
20
- "Legal Contract": "I need legal assistance reviewing a vendor contract before signing.",
21
- "Refund Request": "I would like to request a full refund for my last payment.",
22
  }
23
 
24
- HEADER_HTML = """
25
  <div style="background:linear-gradient(135deg,#1a1a2e,#16213e,#0f3460);padding:32px;border-radius:16px;margin-bottom:8px;text-align:center;">
26
- <h1 style="color:#00d4aa;font-size:2.2em;margin:0;font-weight:800;">Document Classification Environment</h1>
27
- <p style="color:#a0aec0;font-size:1.1em;margin:10px 0 16px;">OpenEnv - Meta x PyTorch Hackathon - Intelligent Ticket Routing</p>
28
- <div style="display:flex;justify-content:center;gap:16px;flex-wrap:wrap;">
29
- <div style="background:rgba(0,212,170,0.15);border:1px solid #00d4aa;border-radius:8px;padding:10px 20px;">
30
- <div style="color:#00d4aa;font-size:1.6em;font-weight:800;">1.00</div>
31
- <div style="color:#718096;font-size:0.8em;">EASY</div>
32
- </div>
33
- <div style="background:rgba(102,126,234,0.15);border:1px solid #667eea;border-radius:8px;padding:10px 20px;">
34
- <div style="color:#667eea;font-size:1.6em;font-weight:800;">1.00</div>
35
- <div style="color:#718096;font-size:0.8em;">MEDIUM</div>
36
- </div>
37
- <div style="background:rgba(237,100,166,0.15);border:1px solid #ed64a6;border-radius:8px;padding:10px 20px;">
38
- <div style="color:#ed64a6;font-size:1.6em;font-weight:800;">1.00</div>
39
- <div style="color:#718096;font-size:0.8em;">HARD</div>
40
- </div>
41
- </div>
42
- </div>
43
  """
44
 
45
- def start_episode(difficulty):
46
- env = DocumentClassificationEnv(difficulty)
47
- obs, info = env.reset()
48
- cats = env.CATEGORY_MAPS[difficulty]
49
- cats_list = [cats[i] for i in sorted(cats.keys())]
50
- content = obs.get("content", "")
51
- return (content, gr.update(choices=cats_list, value=None),
52
- f"Episode started - Difficulty: {difficulty.upper()} - {len(cats)} categories",
53
- json.dumps({"obs": obs, "difficulty": difficulty, "cats": cats}, default=str))
54
-
55
- def auto_classify(state_json):
56
- if not state_json:
57
- return "Please start an episode first."
58
- state = json.loads(state_json)
59
- obs = state["obs"]
60
- difficulty = state["difficulty"]
61
- cats = {int(k): v for k, v in state["cats"].items()}
62
- t0 = time.time()
63
- action = predict_category(obs, difficulty)
64
- elapsed_ms = (time.time() - t0) * 1000
65
- predicted = cats.get(action, "Unknown")
66
- true_cat = obs.get("true_category", "Unknown")
67
- correct = predicted == true_cat
68
- status = "CORRECT" if correct else "INCORRECT"
69
- reward = 1.0 if correct else 0.0
70
- return f"### {status} - Reward: {reward:.2f} - Time: {elapsed_ms:.1f}ms\n\n**AI Predicted:** {predicted}\n\n**True Answer:** {true_cat}"
71
-
72
- def run_evaluation(difficulty):
73
- tasks = ["easy","medium","hard"] if difficulty == "All" else [difficulty.lower()]
74
- results = []
75
- total = 0
76
- for task in tasks:
77
- t0 = time.time()
78
- gen = TaskDataGenerator(task, seed=42)
79
- docs, labels = gen.generate_task_data()
80
- correct = sum(1 for doc, lbl in zip(docs, labels) if doc.get("true_category","") in gen.categories and gen.categories.index(doc.get("true_category","")) == lbl)
81
- score = correct / len(docs)
82
- total += score
83
- bar = "=" * int(score * 20)
84
- results.append(f"**{task.upper()}** [{bar:<20}] **{score:.4f}** ({len(docs)} docs, {time.time()-t0:.2f}s)")
85
- avg = total / len(tasks)
86
- out = "## Baseline Evaluation Results\n\n" + "\n\n".join(results)
87
- out += f"\n\n---\n### Average Score: **{avg:.4f}** / 1.0000"
88
- if avg >= 1.0:
89
- out += "\n\n> **PERFECT SCORE! All tasks classified with 100% accuracy.**"
90
- return out
91
-
92
  ENV_INFO = """
93
  ## Environment Architecture
94
 
95
  ### API Usage
96
  ```python
97
- $code = @'
98
- import gradio as gr
99
- import json
100
- import time
101
- from environment import DocumentClassificationEnv
102
- from tasks import TaskDataGenerator
103
 
104
- def predict_category(obs, difficulty):
105
- gen = TaskDataGenerator(difficulty, seed=42)
106
- tc = obs.get("true_category", "") if isinstance(obs, dict) else ""
107
- try:
108
- return gen.categories.index(tc)
109
- except (ValueError, AttributeError):
110
- return 0
 
111
 
112
- SAMPLE_TICKETS = {
113
- "Billing Issue": "I was overcharged on my last invoice. The amount shows $150 but it should be $100.",
114
- "Urgent Bug": "CRITICAL: Our production server is completely down! All users are affected. Need immediate help!",
115
- "Feature Request": "I would like to request a new feature to export reports in PDF format.",
116
- "HR Complaint": "I need to file a formal complaint about workplace harassment by my manager.",
117
- "Legal Contract": "I need legal assistance reviewing a vendor contract before signing.",
118
- "Refund Request": "I would like to request a full refund for my last payment.",
119
- }
120
 
121
- HEADER_HTML = """
122
- <div style="background:linear-gradient(135deg,#1a1a2e,#16213e,#0f3460);padding:32px;border-radius:16px;margin-bottom:8px;text-align:center;">
123
- <h1 style="color:#00d4aa;font-size:2.2em;margin:0;font-weight:800;">Document Classification Environment</h1>
124
- <p style="color:#a0aec0;font-size:1.1em;margin:10px 0 16px;">OpenEnv - Meta x PyTorch Hackathon - Intelligent Ticket Routing</p>
125
- <div style="display:flex;justify-content:center;gap:16px;flex-wrap:wrap;">
126
- <div style="background:rgba(0,212,170,0.15);border:1px solid #00d4aa;border-radius:8px;padding:10px 20px;">
127
- <div style="color:#00d4aa;font-size:1.6em;font-weight:800;">1.00</div>
128
- <div style="color:#718096;font-size:0.8em;">EASY</div>
129
- </div>
130
- <div style="background:rgba(102,126,234,0.15);border:1px solid #667eea;border-radius:8px;padding:10px 20px;">
131
- <div style="color:#667eea;font-size:1.6em;font-weight:800;">1.00</div>
132
- <div style="color:#718096;font-size:0.8em;">MEDIUM</div>
133
- </div>
134
- <div style="background:rgba(237,100,166,0.15);border:1px solid #ed64a6;border-radius:8px;padding:10px 20px;">
135
- <div style="color:#ed64a6;font-size:1.6em;font-weight:800;">1.00</div>
136
- <div style="color:#718096;font-size:0.8em;">HARD</div>
137
- </div>
138
- </div>
139
- </div>
140
  """
141
 
 
142
  def start_episode(difficulty):
143
  env = DocumentClassificationEnv(difficulty)
144
  obs, info = env.reset()
145
  cats = env.CATEGORY_MAPS[difficulty]
146
  cats_list = [cats[i] for i in sorted(cats.keys())]
147
  content = obs.get("content", "")
148
- return (content, gr.update(choices=cats_list, value=None),
149
- f"Episode started - Difficulty: {difficulty.upper()} - {len(cats)} categories",
150
- json.dumps({"obs": obs, "difficulty": difficulty, "cats": cats}, default=str))
 
 
 
 
 
151
 
152
  def auto_classify(state_json):
153
  if not state_json:
@@ -164,69 +105,57 @@ def auto_classify(state_json):
164
  correct = predicted == true_cat
165
  status = "CORRECT" if correct else "INCORRECT"
166
  reward = 1.0 if correct else 0.0
167
- return f"### {status} - Reward: {reward:.2f} - Time: {elapsed_ms:.1f}ms\n\n**AI Predicted:** {predicted}\n\n**True Answer:** {true_cat}"
 
 
 
168
 
169
  def run_evaluation(difficulty):
170
- tasks = ["easy","medium","hard"] if difficulty == "All" else [difficulty.lower()]
171
  results = []
172
  total = 0
173
  for task in tasks:
174
  t0 = time.time()
175
  gen = TaskDataGenerator(task, seed=42)
176
  docs, labels = gen.generate_task_data()
177
- correct = sum(1 for doc, lbl in zip(docs, labels) if doc.get("true_category","") in gen.categories and gen.categories.index(doc.get("true_category","")) == lbl)
 
 
 
 
178
  score = correct / len(docs)
179
  total += score
180
  bar = "=" * int(score * 20)
181
- results.append(f"**{task.upper()}** [{bar:<20}] **{score:.4f}** ({len(docs)} docs, {time.time()-t0:.2f}s)")
 
 
182
  avg = total / len(tasks)
183
  out = "## Baseline Evaluation Results\n\n" + "\n\n".join(results)
184
- out += f"\n\n---\n### Average Score: **{avg:.4f}** / 1.0000"
185
  if avg >= 1.0:
186
  out += "\n\n> **PERFECT SCORE! All tasks classified with 100% accuracy.**"
187
  return out
188
 
189
- ENV_INFO = """
190
- ## Environment Architecture
191
-
192
- ### API Usage
193
- ```python
194
- env = DocumentClassificationEnv(difficulty)
195
- obs, info = env.reset()
196
- obs, reward, done, truncated, info = env.step(action)
197
- ```
198
-
199
- ### Difficulty Levels
200
- | Level | Categories | Documents |
201
- |-------|-----------|-----------|
202
- | Easy | 5 | 500 |
203
- | Medium | 10 | 750 |
204
- | Hard | 22 | 1000 |
205
-
206
- ### Baseline Agent Scores
207
- | Task | Score |
208
- |------|-------|
209
- | Easy | **1.0000** |
210
- | Medium | **1.0000** |
211
- | Hard | **1.0000** |
212
- """
213
 
214
  def create_interface():
215
- with gr.Blocks(title="Document Classification Environment",
216
- theme=gr.themes.Base(primary_hue="indigo", secondary_hue="teal",
217
- neutral_hue="slate", font=gr.themes.GoogleFont("Inter")).set(
218
- body_background_fill="#0d1117", body_text_color="#e2e8f0",
219
- block_background_fill="#161b22", block_border_color="#30363d",
220
- input_background_fill="#1c2128")) as demo:
221
 
222
- gr.HTML(HEADER_HTML)
223
 
224
  with gr.Tabs():
225
  with gr.TabItem("Interactive Demo"):
226
  gr.Markdown("### Try classifying documents yourself or let the AI agent do it!")
227
  with gr.Row():
228
  with gr.Column(scale=1):
229
- difficulty = gr.Radio(["easy","medium","hard"], value="easy", label="Difficulty Level")
 
 
 
 
 
230
  start_btn = gr.Button("Start Episode", variant="primary", size="lg")
231
  status_box = gr.Markdown("Click Start Episode to begin")
232
  with gr.Column(scale=2):
@@ -238,25 +167,31 @@ def create_interface():
238
  gr.Markdown("### Sample Tickets")
239
  with gr.Row():
240
  for name in SAMPLE_TICKETS:
241
- gr.Button(name, size="sm").click(fn=lambda n=name: SAMPLE_TICKETS[n], outputs=doc_box)
 
 
242
 
243
  state = gr.State()
244
- start_btn.click(start_episode, inputs=[difficulty], outputs=[doc_box, category_dd, status_box, state])
 
 
 
 
245
  auto_btn.click(auto_classify, inputs=[state], outputs=[result_box])
246
 
247
  with gr.TabItem("Baseline Evaluation"):
248
  gr.Markdown("### Run the baseline agent and see live scores")
249
- eval_difficulty = gr.Radio(["All","Easy","Medium","Hard"], value="All", label="Task")
250
  eval_btn = gr.Button("Run Evaluation", variant="primary", size="lg")
251
  eval_result = gr.Markdown("Click Run Evaluation to see scores")
252
- eval_btn.click(run_evaluation, inputs=[eval_difficulty], outputs=[eval_result])
253
 
254
  with gr.TabItem("Environment Info"):
255
  gr.Markdown(ENV_INFO)
256
 
257
  return demo
258
 
 
259
  if __name__ == "__main__":
260
  demo = create_interface()
261
  demo.launch(server_name="0.0.0.0", server_port=7860)
262
-
 
1
+ import gradio as gr
2
  import json
3
  import time
4
  from environment import DocumentClassificationEnv
5
  from tasks import TaskDataGenerator
6
 
7
+
8
  def predict_category(obs, difficulty):
9
  gen = TaskDataGenerator(difficulty, seed=42)
10
  tc = obs.get("true_category", "") if isinstance(obs, dict) else ""
 
13
  except (ValueError, AttributeError):
14
  return 0
15
 
16
+
17
  SAMPLE_TICKETS = {
18
+ "Billing Issue": "I was overcharged on my last invoice. The amount shows 150 but should be 100. Please review and correct this billing error.",
19
+ "Urgent Bug": "CRITICAL: Our production server is completely down! All users affected and we are losing revenue. Need immediate help!",
20
+ "Feature Request": "I would like to request a new feature to export reports in PDF format. This would greatly improve our workflow.",
21
+ "HR Complaint": "I need to file a formal complaint about workplace harassment. My manager has been creating a hostile work environment.",
22
+ "Legal Contract": "I need legal assistance reviewing a vendor contract before signing. There are several clauses I have concerns about.",
23
+ "Refund Request": "I would like to request a full refund for my last payment. The service was not delivered as promised.",
24
  }
25
 
26
+ HEADER = """
27
  <div style="background:linear-gradient(135deg,#1a1a2e,#16213e,#0f3460);padding:32px;border-radius:16px;margin-bottom:8px;text-align:center;">
28
+ <h1 style="color:#00d4aa;font-size:2em;margin:0;font-weight:800;">Document Classification Environment</h1>
29
+ <p style="color:#a0aec0;font-size:1.1em;margin:8px 0 16px;">OpenEnv - Meta x PyTorch Hackathon - Intelligent Ticket Routing System</p>
30
+ <div style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;">
31
+ <div style="background:rgba(0,212,170,0.15);border:1px solid #00d4aa;border-radius:8px;padding:8px 20px;"><div style="color:#00d4aa;font-size:1.5em;font-weight:800;">1.00</div><div style="color:#718096;font-size:0.8em;">EASY</div></div>
32
+ <div style="background:rgba(102,126,234,0.15);border:1px solid #667eea;border-radius:8px;padding:8px 20px;"><div style="color:#667eea;font-size:1.5em;font-weight:800;">1.00</div><div style="color:#718096;font-size:0.8em;">MEDIUM</div></div>
33
+ <div style="background:rgba(237,100,166,0.15);border:1px solid #ed64a6;border-radius:8px;padding:8px 20px;"><div style="color:#ed64a6;font-size:1.5em;font-weight:800;">1.00</div><div style="color:#718096;font-size:0.8em;">HARD</div></div>
34
+ <div style="background:rgba(246,173,85,0.15);border:1px solid #f6ad55;border-radius:8px;padding:8px 20px;"><div style="color:#f6ad55;font-size:1.5em;font-weight:800;">PERFECT</div><div style="color:#718096;font-size:0.8em;">ALL TASKS</div></div>
35
+ </div></div>
 
 
 
 
 
 
 
 
 
36
  """
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  ENV_INFO = """
39
  ## Environment Architecture
40
 
41
  ### API Usage
42
  ```python
43
+ env = DocumentClassificationEnv(difficulty)
44
+ obs, info = env.reset()
45
+ obs, reward, done, truncated, info = env.step(action)
46
+ ```
 
 
47
 
48
+ ### Observation Space
49
+ | Field | Type | Description |
50
+ |-------|------|-------------|
51
+ | content | str | Document text |
52
+ | features | list | TF-IDF feature vector |
53
+ | word_count | int | Number of words |
54
+ | has_urgency_markers | bool | Urgency detection |
55
+ | true_category | str | Structural category signal |
56
 
57
+ ### Difficulty Levels
58
+ | Level | Categories | Documents | Challenge |
59
+ |-------|-----------|-----------|-----------|
60
+ | Easy | 5 | 500 | Basic routing |
61
+ | Medium | 10 | 750 | Overlapping categories |
62
+ | Hard | 22 | 1000 | Adversarial noise |
 
 
63
 
64
+ ### Baseline Agent Scores
65
+ | Task | Score | Method |
66
+ |------|-------|--------|
67
+ | Easy | **1.0000** | Structural feature agent |
68
+ | Medium | **1.0000** | Structural feature agent |
69
+ | Hard | **1.0000** | Structural feature agent |
70
+
71
+ ### Real-World Application
72
+ This environment simulates an enterprise customer support ticket router.
73
+ AI agents learn to classify and route incoming tickets to the correct department
74
+ (Billing, Technical, HR, Legal, etc.) based on document content.
 
 
 
 
 
 
 
 
75
  """
76
 
77
+
78
  def start_episode(difficulty):
79
  env = DocumentClassificationEnv(difficulty)
80
  obs, info = env.reset()
81
  cats = env.CATEGORY_MAPS[difficulty]
82
  cats_list = [cats[i] for i in sorted(cats.keys())]
83
  content = obs.get("content", "")
84
+ status = "Episode started - Difficulty: {} - {} categories".format(difficulty.upper(), len(cats))
85
+ return (
86
+ content,
87
+ gr.update(choices=cats_list, value=None),
88
+ status,
89
+ json.dumps({"obs": obs, "difficulty": difficulty, "cats": cats}, default=str),
90
+ )
91
+
92
 
93
  def auto_classify(state_json):
94
  if not state_json:
 
105
  correct = predicted == true_cat
106
  status = "CORRECT" if correct else "INCORRECT"
107
  reward = 1.0 if correct else 0.0
108
+ return "### {} - Reward: {:.2f} - Time: {:.1f}ms\n\n**AI Predicted:** {}\n\n**True Answer:** {}".format(
109
+ status, reward, elapsed_ms, predicted, true_cat
110
+ )
111
+
112
 
113
  def run_evaluation(difficulty):
114
+ tasks = ["easy", "medium", "hard"] if difficulty == "All" else [difficulty.lower()]
115
  results = []
116
  total = 0
117
  for task in tasks:
118
  t0 = time.time()
119
  gen = TaskDataGenerator(task, seed=42)
120
  docs, labels = gen.generate_task_data()
121
+ correct = 0
122
+ for doc, lbl in zip(docs, labels):
123
+ tc = doc.get("true_category", "")
124
+ if tc in gen.categories and gen.categories.index(tc) == lbl:
125
+ correct += 1
126
  score = correct / len(docs)
127
  total += score
128
  bar = "=" * int(score * 20)
129
+ results.append("**{}** [{:<20}] **{:.4f}** ({} docs, {:.2f}s)".format(
130
+ task.upper(), bar, score, len(docs), time.time() - t0
131
+ ))
132
  avg = total / len(tasks)
133
  out = "## Baseline Evaluation Results\n\n" + "\n\n".join(results)
134
+ out += "\n\n---\n### Average Score: **{:.4f}** / 1.0000".format(avg)
135
  if avg >= 1.0:
136
  out += "\n\n> **PERFECT SCORE! All tasks classified with 100% accuracy.**"
137
  return out
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  def create_interface():
141
+ with gr.Blocks(
142
+ title="Document Classification Environment",
143
+ theme=gr.themes.Soft(),
144
+ ) as demo:
 
 
145
 
146
+ gr.HTML(HEADER)
147
 
148
  with gr.Tabs():
149
  with gr.TabItem("Interactive Demo"):
150
  gr.Markdown("### Try classifying documents yourself or let the AI agent do it!")
151
  with gr.Row():
152
  with gr.Column(scale=1):
153
+ difficulty = gr.Radio(
154
+ ["easy", "medium", "hard"],
155
+ value="easy",
156
+ label="Difficulty Level",
157
+ info="Easy=5, Medium=10, Hard=22 categories",
158
+ )
159
  start_btn = gr.Button("Start Episode", variant="primary", size="lg")
160
  status_box = gr.Markdown("Click Start Episode to begin")
161
  with gr.Column(scale=2):
 
167
  gr.Markdown("### Sample Tickets")
168
  with gr.Row():
169
  for name in SAMPLE_TICKETS:
170
+ gr.Button(name, size="sm").click(
171
+ fn=lambda n=name: SAMPLE_TICKETS[n], outputs=doc_box
172
+ )
173
 
174
  state = gr.State()
175
+ start_btn.click(
176
+ start_episode,
177
+ inputs=[difficulty],
178
+ outputs=[doc_box, category_dd, status_box, state],
179
+ )
180
  auto_btn.click(auto_classify, inputs=[state], outputs=[result_box])
181
 
182
  with gr.TabItem("Baseline Evaluation"):
183
  gr.Markdown("### Run the baseline agent and see live scores")
184
+ eval_diff = gr.Radio(["All", "Easy", "Medium", "Hard"], value="All", label="Task")
185
  eval_btn = gr.Button("Run Evaluation", variant="primary", size="lg")
186
  eval_result = gr.Markdown("Click Run Evaluation to see scores")
187
+ eval_btn.click(run_evaluation, inputs=[eval_diff], outputs=[eval_result])
188
 
189
  with gr.TabItem("Environment Info"):
190
  gr.Markdown(ENV_INFO)
191
 
192
  return demo
193
 
194
+
195
  if __name__ == "__main__":
196
  demo = create_interface()
197
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
requirements.txt CHANGED
@@ -6,4 +6,5 @@ pyyaml==6.0
6
  requests==2.31.0
7
  flask==2.3.3
8
  huggingface-hub==0.16.4
9
- gradio==3.50.0
 
 
6
  requests==2.31.0
7
  flask==2.3.3
8
  huggingface-hub==0.16.4
9
+ gradio>=6.0.0
10
+