import gradio as gr import threading import os import pickle from flask import Flask, request, jsonify from environment import DocumentClassificationEnv from baseline_inference import run_task, load_or_train from agent import TicketAgent print("Pre-training models...") models = {} for d in ["easy", "medium", "hard"]: models[d] = load_or_train(d) print(f" {d} model ready!") print("All models ready!") agent = TicketAgent() print("Agent ready!") flask_app = Flask('app') @flask_app.route('/classify', methods=['POST']) def classify(): data = request.get_json() text = data.get('text', '') difficulty = data.get('difficulty', 'easy') model = models.get(difficulty) if model is None: return jsonify({'error': 'Invalid difficulty'}), 400 prediction = int(model.predict([text])[0]) return jsonify({'category': prediction}) @flask_app.route('/health', methods=['GET']) def health(): return jsonify({'status': 'ok'}) def run_flask(): flask_app.run(host='0.0.0.0', port=7861, debug=False) flask_thread = threading.Thread(target=run_flask, daemon=True) flask_thread.start() def classify_document(text, difficulty): if not text.strip(): return "Please enter some text.", "", "" model = models.get(difficulty) if model is None: return "Invalid difficulty selected.", "", "" prediction = int(model.predict([text])[0]) env = DocumentClassificationEnv(task_difficulty=difficulty, seed=42) category_name = env.categories.get(prediction, str(prediction)) agent_response = agent.process(text, prediction, category_name) return f"Category ID: {prediction}", f"Category Name: {category_name}", agent_response def run_benchmark(difficulty): score, elapsed = run_task(difficulty) return f"Score: {score:.4f} | Time: {elapsed:.1f}s" with gr.Blocks(title="Document Classification") as demo: gr.Markdown("# Document Classification Environment") gr.Markdown("Classify documents using trained ML models across different difficulty levels.") with gr.Tab("Classify Document"): with gr.Row(): with gr.Column(): input_text = gr.Textbox( label="Document Text", placeholder="Enter document text here...", lines=5 ) difficulty_dropdown = gr.Dropdown( choices=["easy", "medium", "hard"], value="easy", label="Difficulty Level" ) classify_btn = gr.Button("Classify", variant="primary") with gr.Column(): output_id = gr.Textbox(label="Category ID") output_name = gr.Textbox(label="Category Name") output_agent = gr.Textbox(label="Agent Response", lines=3) classify_btn.click( fn=classify_document, inputs=[input_text, difficulty_dropdown], outputs=[output_id, output_name, output_agent] ) with gr.Tab("Benchmark"): bench_difficulty = gr.Dropdown( choices=["easy", "medium", "hard"], value="easy", label="Difficulty Level" ) bench_btn = gr.Button("Run Benchmark", variant="primary") bench_output = gr.Textbox(label="Result") bench_btn.click( fn=run_benchmark, inputs=[bench_difficulty], outputs=[bench_output] ) demo.launch(server_name="0.0.0.0", server_port=7860)