Spaces:
Sleeping
Sleeping
| import random | |
| import json | |
| import subprocess | |
| from flask import Flask, render_template, request, session, jsonify, send_file | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| import csv | |
| from datetime import datetime | |
| with open("intents.json", encoding="utf-8") as f: | |
| intents = json.load(f) | |
| MODEL_PATH = "./intent_model" | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) | |
| model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH) | |
| model.eval() | |
| app = Flask(__name__) | |
| app.secret_key = "supersecretkey" | |
| user_context = {"awaiting_transaction": False} | |
| UNKNOWN_FILE = "unknown.csv" | |
| THRESHOLD = 0.85 | |
| def auto_commit_unknown(): | |
| """يرفع تلقائيًا ملف unknown.csv إلى مشروع Hugging Face""" | |
| try: | |
| subprocess.run(["git", "config", "--global", "user.email", "bot@huggingface.co"]) | |
| subprocess.run(["git", "config", "--global", "user.name", "HuggingFace Bot"]) | |
| subprocess.run(["git", "add", "unknown.csv"]) | |
| subprocess.run(["git", "commit", "-m", "Auto-update unknown.csv with new logs"], check=False) | |
| subprocess.run(["git", "push"], check=False) | |
| print(" تم رفع unknown.csv بنجاح إلى المشروع.") | |
| except Exception as e: | |
| print(" Auto commit failed:", e) | |
| def log_unknown(text, tag, prob): | |
| with open(UNKNOWN_FILE, "a", encoding="utf-8", newline="") as f: | |
| writer = csv.writer(f) | |
| writer.writerow([datetime.now().isoformat(), text, tag, f"{prob:.3f}"]) | |
| auto_commit_unknown() | |
| def predict_intent(text): | |
| with torch.no_grad(): | |
| inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=64) | |
| outputs = model(**inputs) | |
| probs = torch.softmax(outputs.logits, dim=-1)[0] | |
| conf, idx = torch.max(probs, dim=0) | |
| tag = model.config.id2label[idx.item()] | |
| return tag, conf.item() | |
| def get_response(user_input): | |
| global user_context | |
| if user_context["awaiting_transaction"]: | |
| user_context["awaiting_transaction"] = False | |
| return f"تم العثور على معاملتك (رقم {user_input}) وهي قيد المراجعة." | |
| tag, prob = predict_intent(user_input) | |
| if prob < THRESHOLD or (tag == "goodbye" and prob < 0.95): | |
| log_unknown(user_input, tag, prob) | |
| return "ما فهمت قصدك ، جرب تسألني عن الدوام، الرخص، البلاغات أو المعاملات." | |
| if tag == "inquiry": | |
| user_context["awaiting_transaction"] = True | |
| for intent in intents["intents"]: | |
| if intent["tag"] == tag: | |
| return random.choice(intent["responses"]) | |
| log_unknown(user_input, tag, prob) | |
| return "ما فهمت قصدك ، جرب تسألني عن الدوام، الرخص، البلاغات أو المعاملات." | |
| def home(): | |
| if "chat" not in session: | |
| session["chat"] = [] | |
| return render_template("index.html", chat=session["chat"]) | |
| def api_chat(): | |
| user_input = request.json.get("user_input") | |
| reply = get_response(user_input) | |
| if "chat" not in session: | |
| session["chat"] = [] | |
| session["chat"].append({"role": "user", "text": user_input}) | |
| session["chat"].append({"role": "bot", "text": reply}) | |
| session.modified = True | |
| return jsonify({"reply": reply}) | |
| def clear_chat(): | |
| session.pop("chat", None) | |
| return jsonify({"success": True}) | |
| def download_unknown(): | |
| try: | |
| return send_file(UNKNOWN_FILE, as_attachment=True) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860, debug=False) | |