muffin2006 commited on
Commit
72ca8da
ยท
verified ยท
1 Parent(s): a1b6963

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -110
app.py CHANGED
@@ -5,61 +5,103 @@ from environment import DocumentClassificationEnv
5
  from baseline_inference import run_task, load_or_train
6
  from agent import TicketAgent
7
 
 
 
8
  # =========================
9
- # ๐Ÿš€ LOAD MODELS
10
  # =========================
11
- print("Pre-training models...")
12
- models = {d: load_or_train(d) for d in ["easy", "medium", "hard"]}
13
- print("All models ready!")
 
 
 
 
14
 
15
  agent = TicketAgent(model_dir=".")
16
 
17
  # =========================
18
- # ๐ŸŽฏ UI LOGIC
19
  # =========================
20
-
21
  env_state = {"env": None}
22
 
 
 
 
 
23
  def create_env(difficulty):
24
- env = DocumentClassificationEnv(task_difficulty=difficulty)
25
- obs, _ = env.reset()
26
- env_state["env"] = env
27
- return f"โœ… Environment ready ({difficulty})", obs["content"]
 
 
 
28
 
29
  def classify_doc(idx):
30
- env = env_state["env"]
31
- if not env:
32
- return "โš ๏ธ Create environment first!", ""
33
- obs, reward, done, _, info = env.step(int(idx))
34
- msg = f"๐ŸŽฏ Reward: {reward} | Correct: {info['is_correct']}"
35
- if done:
36
- msg += "\n๐Ÿ Episode finished!"
37
- return msg, obs["content"]
 
 
 
 
 
 
 
38
 
39
  def run_baseline_all():
40
- rows = []
41
- for d in ["easy","medium","hard"]:
42
- score, t = run_task(d)
43
- rows.append([d.upper(), score, score*100, t])
44
- return pd.DataFrame(rows, columns=["Task","Score","Accuracy (%)","Time (s)"])
 
 
 
 
45
 
46
  def process_ticket_ui(text, difficulty):
47
- if not text.strip():
48
- return "Enter ticket!", "", "", "", "", ""
49
-
50
- res = agent.process_ticket(text, difficulty=difficulty)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- return (
53
- f"{res['category']} ({res['confidence']*100:.1f}%)",
54
- res["priority"],
55
- res["department"],
56
- "\n".join([f"{c}: {p*100:.1f}%" for c,p in res["top3"]]),
57
- res["ref_id"],
58
- res["reply"]
59
- )
60
 
61
  # =========================
62
- # ๐ŸŽจ CUSTOM THEME + CSS
63
  # =========================
64
 
65
  custom_css = """
@@ -71,9 +113,9 @@ body {
71
  font-family: 'Poppins', sans-serif;
72
  }
73
 
74
- h1, h2, h3 {
75
  text-align: center;
76
- color: #f8fafc;
77
  }
78
 
79
  textarea, input {
@@ -88,53 +130,31 @@ button {
88
  button:hover {
89
  transform: scale(1.05);
90
  }
91
-
92
- .card {
93
- background: rgba(255,255,255,0.05);
94
- backdrop-filter: blur(10px);
95
- padding: 15px;
96
- border-radius: 16px;
97
- }
98
  """
99
 
100
- # =========================
101
- # ๐ŸŽจ UI DESIGN (UPGRADED)
102
- # =========================
103
-
104
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
105
 
106
- gr.Markdown("""
107
- # ๐Ÿค– AI Ticket Intelligence System
108
- ### โšก Smart Classification โ€ข ๐ŸŽฏ Priority Detection โ€ข ๐Ÿค Auto Routing
109
- """)
110
 
111
- # =========================
112
- # ๐Ÿค– SMART AGENT
113
- # =========================
114
- with gr.Tab("๐Ÿค– Smart AI Agent"):
115
  with gr.Row():
116
- with gr.Column(scale=1):
117
- gr.Markdown("### ๐Ÿ“ Input Ticket")
118
- ticket_input = gr.Textbox(lines=6, placeholder="Enter user issue here...")
 
119
 
120
- difficulty = gr.Radio(
121
- ["easy","medium","hard"],
122
- value="medium",
123
- label="โš™๏ธ Difficulty Mode"
124
- )
 
125
 
126
- btn = gr.Button("๐Ÿš€ Analyze Ticket", variant="primary")
127
-
128
- with gr.Column(scale=1):
129
- gr.Markdown("### ๐Ÿ“Š AI Predictions")
130
-
131
- cat = gr.Textbox(label="๐Ÿท Category")
132
- pri = gr.Textbox(label="โšก Priority")
133
- dept = gr.Textbox(label="๐Ÿข Department")
134
- top3 = gr.Textbox(label="๐Ÿ“ˆ Top Predictions")
135
- ref = gr.Textbox(label="๐ŸŽซ Ticket ID")
136
-
137
- reply = gr.Textbox(label="๐Ÿ“ง Auto Generated Reply", lines=5)
138
 
139
  btn.click(
140
  process_ticket_ui,
@@ -142,61 +162,46 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
142
  outputs=[cat, pri, dept, top3, ref, reply]
143
  )
144
 
145
- # =========================
146
  # ๐ŸŽฎ SIMULATOR
147
- # =========================
148
- with gr.Tab("๐ŸŽฎ AI Simulator"):
149
- gr.Markdown("### ๐Ÿง  Train & Test Your Model")
150
-
151
- diff = gr.Radio(["easy","medium","hard"], value="easy", label="Difficulty")
152
  btn_create = gr.Button("Create Environment")
153
 
154
  status = gr.Textbox(label="Status")
155
  doc = gr.Textbox(label="Document", lines=5)
156
 
157
  idx = gr.Number(label="Category Index")
158
- btn_step = gr.Button("Classify Document")
159
 
160
  result = gr.Textbox(label="Result")
161
 
162
  btn_create.click(create_env, inputs=diff, outputs=[status, doc])
163
  btn_step.click(classify_doc, inputs=idx, outputs=[result, doc])
164
 
165
- # =========================
166
  # ๐Ÿ“Š PERFORMANCE
167
- # =========================
168
- with gr.Tab("๐Ÿ“Š Model Performance"):
169
- gr.Markdown("### ๐Ÿ“ˆ Evaluate AI Models")
170
-
171
- btn_eval = gr.Button("Run Evaluation", variant="primary")
172
  table = gr.Dataframe()
173
 
174
  btn_eval.click(run_baseline_all, outputs=table)
175
 
176
- # =========================
177
  # โ„น๏ธ ABOUT
178
- # =========================
179
- with gr.Tab("โ„น๏ธ About System"):
180
  gr.Markdown("""
181
- ## ๐Ÿš€ Features
182
- - AI-based ticket classification
183
- - Smart priority detection
184
- - Automatic department routing
185
- - Reinforcement learning simulator
186
-
187
- ## ๐Ÿ›  Tech Stack
188
- - Gradio UI
189
- - Machine Learning Models
190
- - Custom RL Environment
191
-
192
- ## ๐Ÿ’ก Use Case
193
- - Customer support automation
194
- - IT helpdesk optimization
195
- - Enterprise workflow management
196
  """)
197
 
198
  # =========================
199
- # ๐Ÿš€ RUN APP
200
  # =========================
201
  if __name__ == "__main__":
202
- demo.launch(server_name="0.0.0.0", port=7860)
 
5
  from baseline_inference import run_task, load_or_train
6
  from agent import TicketAgent
7
 
8
+ print("๐Ÿš€ Space starting...")
9
+
10
  # =========================
11
+ # ๐Ÿง  LAZY MODEL LOADING (HF SAFE)
12
  # =========================
13
+ models = {}
14
+
15
+ def get_model(difficulty):
16
+ if difficulty not in models:
17
+ print(f"Loading model: {difficulty}")
18
+ models[difficulty] = load_or_train(difficulty)
19
+ return models[difficulty]
20
 
21
  agent = TicketAgent(model_dir=".")
22
 
23
  # =========================
24
+ # ๐ŸŽฏ STATE
25
  # =========================
 
26
  env_state = {"env": None}
27
 
28
+ # =========================
29
+ # ๐Ÿ›ก๏ธ SAFE FUNCTIONS
30
+ # =========================
31
+
32
  def create_env(difficulty):
33
+ try:
34
+ env = DocumentClassificationEnv(task_difficulty=difficulty)
35
+ obs, _ = env.reset()
36
+ env_state["env"] = env
37
+ return f"โœ… Environment ready ({difficulty})", obs.get("content", "")
38
+ except Exception as e:
39
+ return f"โŒ Error: {str(e)}", ""
40
 
41
  def classify_doc(idx):
42
+ try:
43
+ env = env_state["env"]
44
+ if not env:
45
+ return "โš ๏ธ Create environment first!", ""
46
+
47
+ idx = int(idx)
48
+ obs, reward, done, _, info = env.step(idx)
49
+
50
+ msg = f"๐ŸŽฏ Reward: {reward} | Correct: {info.get('is_correct', False)}"
51
+ if done:
52
+ msg += "\n๐Ÿ Episode finished!"
53
+
54
+ return msg, obs.get("content", "")
55
+ except Exception as e:
56
+ return f"โŒ Error: {str(e)}", ""
57
 
58
  def run_baseline_all():
59
+ try:
60
+ rows = []
61
+ for d in ["easy","medium","hard"]:
62
+ model = get_model(d) # lazy load
63
+ score, t = run_task(d)
64
+ rows.append([d.upper(), score, score*100, t])
65
+ return pd.DataFrame(rows, columns=["Task","Score","Accuracy (%)","Time (s)"])
66
+ except Exception as e:
67
+ return pd.DataFrame([[str(e), "", "", ""]], columns=["Task","Score","Accuracy (%)","Time (s)"])
68
 
69
  def process_ticket_ui(text, difficulty):
70
+ try:
71
+ if not text.strip():
72
+ return "Enter ticket!", "", "", "", "", ""
73
+
74
+ model = get_model(difficulty) # lazy load
75
+
76
+ res = agent.process_ticket(text, difficulty=difficulty)
77
+
78
+ category = res.get("category", "Unknown")
79
+ confidence = res.get("confidence", 0)
80
+ priority = res.get("priority", "N/A")
81
+ department = res.get("department", "N/A")
82
+ ref_id = res.get("ref_id", "N/A")
83
+ reply = res.get("reply", "No reply generated")
84
+
85
+ top3_data = res.get("top3", [])
86
+ if isinstance(top3_data, list):
87
+ top3 = "\n".join([f"{c}: {p*100:.1f}%" for c,p in top3_data])
88
+ else:
89
+ top3 = "N/A"
90
+
91
+ return (
92
+ f"{category} ({confidence*100:.1f}%)",
93
+ priority,
94
+ department,
95
+ top3,
96
+ ref_id,
97
+ reply
98
+ )
99
 
100
+ except Exception as e:
101
+ return f"โŒ Error: {str(e)}", "", "", "", "", ""
 
 
 
 
 
 
102
 
103
  # =========================
104
+ # ๐ŸŽจ MODERN UI (UNIQUE)
105
  # =========================
106
 
107
  custom_css = """
 
113
  font-family: 'Poppins', sans-serif;
114
  }
115
 
116
+ h1, h2 {
117
  text-align: center;
118
+ color: white;
119
  }
120
 
121
  textarea, input {
 
130
  button:hover {
131
  transform: scale(1.05);
132
  }
 
 
 
 
 
 
 
133
  """
134
 
 
 
 
 
135
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
136
 
137
+ gr.Markdown("# ๐Ÿค– AI Ticket Intelligence System")
138
+ gr.Markdown("### Smart โ€ข Fast โ€ข Hackathon Ready ๐Ÿš€")
 
 
139
 
140
+ # -------------------------
141
+ # ๐Ÿค– AGENT
142
+ # -------------------------
143
+ with gr.Tab("๐Ÿค– Smart AI"):
144
  with gr.Row():
145
+ with gr.Column():
146
+ ticket_input = gr.Textbox(lines=6, placeholder="Enter ticket...")
147
+ difficulty = gr.Radio(["easy","medium","hard"], value="medium")
148
+ btn = gr.Button("๐Ÿš€ Analyze")
149
 
150
+ with gr.Column():
151
+ cat = gr.Textbox(label="Category")
152
+ pri = gr.Textbox(label="Priority")
153
+ dept = gr.Textbox(label="Department")
154
+ top3 = gr.Textbox(label="Top Predictions")
155
+ ref = gr.Textbox(label="Ticket ID")
156
 
157
+ reply = gr.Textbox(label="Auto Reply", lines=5)
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  btn.click(
160
  process_ticket_ui,
 
162
  outputs=[cat, pri, dept, top3, ref, reply]
163
  )
164
 
165
+ # -------------------------
166
  # ๐ŸŽฎ SIMULATOR
167
+ # -------------------------
168
+ with gr.Tab("๐ŸŽฎ Simulator"):
169
+ diff = gr.Radio(["easy","medium","hard"], value="easy")
 
 
170
  btn_create = gr.Button("Create Environment")
171
 
172
  status = gr.Textbox(label="Status")
173
  doc = gr.Textbox(label="Document", lines=5)
174
 
175
  idx = gr.Number(label="Category Index")
176
+ btn_step = gr.Button("Classify")
177
 
178
  result = gr.Textbox(label="Result")
179
 
180
  btn_create.click(create_env, inputs=diff, outputs=[status, doc])
181
  btn_step.click(classify_doc, inputs=idx, outputs=[result, doc])
182
 
183
+ # -------------------------
184
  # ๐Ÿ“Š PERFORMANCE
185
+ # -------------------------
186
+ with gr.Tab("๐Ÿ“Š Performance"):
187
+ btn_eval = gr.Button("Run Evaluation")
 
 
188
  table = gr.Dataframe()
189
 
190
  btn_eval.click(run_baseline_all, outputs=table)
191
 
192
+ # -------------------------
193
  # โ„น๏ธ ABOUT
194
+ # -------------------------
195
+ with gr.Tab("โ„น๏ธ About"):
196
  gr.Markdown("""
197
+ - AI ticket classification
198
+ - Priority detection
199
+ - Auto routing
200
+ - RL simulator
 
 
 
 
 
 
 
 
 
 
 
201
  """)
202
 
203
  # =========================
204
+ # ๐Ÿš€ RUN (HF SAFE)
205
  # =========================
206
  if __name__ == "__main__":
207
+ demo.launch()