muffin2006's picture
Update app.py
40c94b6 verified
Raw History Blame Contribute Delete
5.93 kB
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)