import gradio as gr import pandas as pd from environment import DocumentClassificationEnv from baseline_inference import run_task, load_or_train from agent import TicketAgent print("šŸš€ Space starting...") # ========================= # 🧠 LAZY MODEL LOADING # ========================= models = {} def get_model(difficulty): if difficulty not in models: print(f"Loading model: {difficulty}") models[difficulty] = load_or_train(difficulty) return models[difficulty] agent = TicketAgent(model_dir=".") # ========================= # šŸŽÆ STATE # ========================= env_state = {"env": None} # ========================= # šŸ›”ļø SAFE FUNCTIONS # ========================= def create_env(difficulty): try: env = DocumentClassificationEnv(task_difficulty=difficulty) obs, _ = env.reset() env_state["env"] = env return f"āœ… Environment ready ({difficulty})", obs.get("content", "") except Exception as e: return f"āŒ Error: {str(e)}", "" def classify_doc(idx): try: env = env_state["env"] if not env: return "āš ļø Create environment first!", "" idx = int(idx) obs, reward, done, _, info = env.step(idx) msg = f"šŸŽÆ Reward: {reward} | Correct: {info.get('is_correct', False)}" if done: msg += "\nšŸ Episode finished!" return msg, obs.get("content", "") except Exception as e: return f"āŒ Error: {str(e)}", "" def run_baseline_all(): try: rows = [] for d in ["easy","medium","hard"]: get_model(d) score, t = run_task(d) rows.append([d.upper(), score, score*100, t]) return pd.DataFrame( rows, columns=["Task","Score","Accuracy (%)","Time (s)"] ) except Exception as e: return pd.DataFrame( [["ERROR", str(e), "", ""]], columns=["Task","Score","Accuracy (%)","Time (s)"] ) def process_ticket_ui(text, difficulty): try: if not text.strip(): return "Enter ticket!", "", "", "", "", "" get_model(difficulty) res = agent.process_ticket(text, difficulty=difficulty) category = res.get("category", "Unknown") confidence = res.get("confidence", 0) priority = res.get("priority", "N/A") department = res.get("department", "N/A") ref_id = res.get("ref_id", "N/A") reply = res.get("reply", "No reply generated") top3_data = res.get("top3", []) if isinstance(top3_data, list): top3 = "\n".join([ f"{str(c)}: {float(p)*100:.1f}%" for c, p in top3_data if isinstance(p, (int, float)) ]) else: top3 = "N/A" return ( f"{category} ({confidence*100:.1f}%)", priority, department, top3, ref_id, reply ) except Exception as e: return f"āŒ Error: {str(e)}", "", "", "", "", "" # ========================= # šŸŽØ UI DESIGN (NO THEME BUG) # ========================= custom_css = """ body { background: linear-gradient(135deg, #0f172a, #1e293b); } .gradio-container { font-family: Arial, sans-serif; } h1, h2 { text-align: center; color: white; } textarea, input { border-radius: 10px !important; } button { border-radius: 10px !important; transition: 0.3s; } button:hover { transform: scale(1.05); } """ with gr.Blocks(css=custom_css) as demo: gr.Markdown("# šŸ¤– AI Ticket Intelligence System") gr.Markdown("### Smart • Fast • Stable šŸš€") # ------------------------- # šŸ¤– AGENT # ------------------------- with gr.Tab("šŸ¤– Smart AI"): with gr.Row(): with gr.Column(): ticket_input = gr.Textbox(lines=6, placeholder="Enter ticket...") difficulty = gr.Radio(["easy","medium","hard"], value="medium") btn = gr.Button("šŸš€ Analyze") with gr.Column(): cat = gr.Textbox(label="Category") pri = gr.Textbox(label="Priority") dept = gr.Textbox(label="Department") top3 = gr.Textbox(label="Top Predictions") ref = gr.Textbox(label="Ticket ID") reply = gr.Textbox(label="Auto Reply", lines=5) btn.click( process_ticket_ui, inputs=[ticket_input, difficulty], outputs=[cat, pri, dept, top3, ref, reply] ) # ------------------------- # šŸŽ® SIMULATOR # ------------------------- with gr.Tab("šŸŽ® Simulator"): diff = gr.Radio(["easy","medium","hard"], value="easy") btn_create = gr.Button("Create Environment") status = gr.Textbox(label="Status") doc = gr.Textbox(label="Document", lines=5) idx = gr.Number(label="Category Index") btn_step = gr.Button("Classify") result = gr.Textbox(label="Result") btn_create.click(create_env, inputs=diff, outputs=[status, doc]) btn_step.click(classify_doc, inputs=idx, outputs=[result, doc]) # ------------------------- # šŸ“Š PERFORMANCE # ------------------------- with gr.Tab("šŸ“Š Performance"): btn_eval = gr.Button("Run Evaluation") table = gr.Dataframe(type="pandas") btn_eval.click(run_baseline_all, outputs=table) # ------------------------- # ā„¹ļø ABOUT # ------------------------- with gr.Tab("ā„¹ļø About"): gr.Markdown(""" - AI ticket classification - Priority detection - Auto routing - RL simulator """) # ========================= # šŸš€ RUN (FINAL FIX) # ========================= if __name__ == "__main__": demo.launch(server_name="0.0.0.0", share=True)