Download app.py from muffin2006/document-classification-env: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/spaces/muffin2006/document-classification-env/resolve/main/app.py
- Command line
-
hf download hf://spaces/muffin2006/document-classification-env/app.py
-
curl -L -o app.py https://huggingface.co/spaces/muffin2006/document-classification-env/resolve/main/app.py
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) |