Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,16 +19,20 @@ HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
| 19 |
TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 20 |
TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
|
| 21 |
|
| 22 |
-
# MODELS (
|
| 23 |
TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
# GLOBAL ROUTER URL (Jo HF ne manga hai)
|
| 27 |
ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 28 |
|
| 29 |
@app.route('/', methods=['GET'])
|
| 30 |
def home():
|
| 31 |
-
return jsonify({"status": "TS AI Brain (
|
| 32 |
|
| 33 |
@app.route('/api/chat', methods=['POST'])
|
| 34 |
def chat():
|
|
@@ -37,10 +41,10 @@ def chat():
|
|
| 37 |
image_url = None
|
| 38 |
|
| 39 |
if is_form_data or request.files:
|
| 40 |
-
user_message = request.form.get("message", "
|
| 41 |
image_file = request.files.get("image")
|
| 42 |
if image_file:
|
| 43 |
-
# 1. TELEGRAM UPLOAD (
|
| 44 |
tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto"
|
| 45 |
files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)}
|
| 46 |
data = {'chat_id': TG_CHAT_ID}
|
|
@@ -51,7 +55,7 @@ def chat():
|
|
| 51 |
file_info = requests.get(f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}").json()
|
| 52 |
image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
|
| 53 |
except Exception as e:
|
| 54 |
-
return jsonify({"error": "Telegram
|
| 55 |
|
| 56 |
else:
|
| 57 |
data = request.json
|
|
@@ -60,52 +64,53 @@ def chat():
|
|
| 60 |
# LOAD HISTORY
|
| 61 |
doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
|
| 62 |
doc = doc_ref.get()
|
| 63 |
-
history = doc.to_dict().get('messages', []) if doc.exists else [{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}]
|
| 64 |
|
| 65 |
headers = {
|
| 66 |
"Authorization": f"Bearer {HF_TOKEN}",
|
| 67 |
"Content-Type": "application/json",
|
| 68 |
-
"x-wait-for-model": "true"
|
| 69 |
}
|
| 70 |
|
| 71 |
try:
|
|
|
|
| 72 |
if image_url:
|
| 73 |
-
# ---
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
| 89 |
|
| 90 |
-
if
|
| 91 |
-
|
| 92 |
-
else:
|
| 93 |
-
return jsonify({"error": "Router Vision Fail", "api_response": result}), 500
|
| 94 |
|
| 95 |
-
history.append({"role": "user", "content": f"[
|
| 96 |
else:
|
| 97 |
-
# --- TEXT CALL
|
| 98 |
history.append({"role": "user", "content": user_message})
|
| 99 |
payload = {"model": TEXT_MODEL, "messages": history, "max_tokens": 1000}
|
| 100 |
resp = requests.post(ROUTER_URL, headers=headers, json=payload)
|
| 101 |
reply = resp.json()["choices"][0]["message"]["content"]
|
| 102 |
|
|
|
|
| 103 |
history.append({"role": "assistant", "content": reply})
|
| 104 |
doc_ref.set({'messages': history})
|
| 105 |
return jsonify({"reply": reply})
|
| 106 |
|
| 107 |
except Exception as e:
|
| 108 |
-
return jsonify({"error": "
|
| 109 |
|
| 110 |
if __name__ == '__main__':
|
| 111 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 19 |
TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 20 |
TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
|
| 21 |
|
| 22 |
+
# MODELS LIST (Fallback System)
|
| 23 |
TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 24 |
+
# Teen alag providers ke vision models
|
| 25 |
+
VISION_MODELS = [
|
| 26 |
+
"meta-llama/Llama-3.2-11B-Vision-Instruct",
|
| 27 |
+
"Qwen/Qwen2-VL-7B-Instruct",
|
| 28 |
+
"microsoft/Phi-3.5-vision-instruct"
|
| 29 |
+
]
|
| 30 |
|
|
|
|
| 31 |
ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 32 |
|
| 33 |
@app.route('/', methods=['GET'])
|
| 34 |
def home():
|
| 35 |
+
return jsonify({"status": "TS AI Brain (Multi-Vision + Telegram) is Online! 🚀"})
|
| 36 |
|
| 37 |
@app.route('/api/chat', methods=['POST'])
|
| 38 |
def chat():
|
|
|
|
| 41 |
image_url = None
|
| 42 |
|
| 43 |
if is_form_data or request.files:
|
| 44 |
+
user_message = request.form.get("message", "Analyze this image.")
|
| 45 |
image_file = request.files.get("image")
|
| 46 |
if image_file:
|
| 47 |
+
# 1. TELEGRAM UPLOAD (Isme koi panga nahi hai, ye chal raha hai)
|
| 48 |
tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto"
|
| 49 |
files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)}
|
| 50 |
data = {'chat_id': TG_CHAT_ID}
|
|
|
|
| 55 |
file_info = requests.get(f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}").json()
|
| 56 |
image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
|
| 57 |
except Exception as e:
|
| 58 |
+
return jsonify({"error": "Telegram Fail", "details": str(e)}), 500
|
| 59 |
|
| 60 |
else:
|
| 61 |
data = request.json
|
|
|
|
| 64 |
# LOAD HISTORY
|
| 65 |
doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
|
| 66 |
doc = doc_ref.get()
|
| 67 |
+
history = doc.to_dict().get('messages', []) if doc.exists else [{"role": "system", "content": "Tum TS Boss ke personal AI ho. Hinglish mein baat karo."}]
|
| 68 |
|
| 69 |
headers = {
|
| 70 |
"Authorization": f"Bearer {HF_TOKEN}",
|
| 71 |
"Content-Type": "application/json",
|
| 72 |
+
"x-wait-for-model": "true"
|
| 73 |
}
|
| 74 |
|
| 75 |
try:
|
| 76 |
+
reply = ""
|
| 77 |
if image_url:
|
| 78 |
+
# --- 2. MULTI-MODEL VISION FALLBACK ---
|
| 79 |
+
last_error = ""
|
| 80 |
+
for model_name in VISION_MODELS:
|
| 81 |
+
payload = {
|
| 82 |
+
"model": model_name,
|
| 83 |
+
"messages": [{"role": "user", "content": [{"type": "text", "text": user_message}, {"type": "image_url", "image_url": {"url": image_url}}]}],
|
| 84 |
+
"max_tokens": 800
|
| 85 |
+
}
|
| 86 |
+
resp = requests.post(ROUTER_URL, headers=headers, json=payload)
|
| 87 |
+
result = resp.json()
|
| 88 |
+
|
| 89 |
+
if "choices" in result:
|
| 90 |
+
reply = result["choices"]["message"]["content"]
|
| 91 |
+
break # Agar ek model ne jawab de diya, toh loop rok do
|
| 92 |
+
else:
|
| 93 |
+
last_error = result
|
| 94 |
+
print(f"Model {model_name} failed, trying next...")
|
| 95 |
|
| 96 |
+
if not reply:
|
| 97 |
+
return jsonify({"error": "Saare Vision Models down hain!", "last_api_error": last_error}), 500
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
history.append({"role": "user", "content": f"[Boss sent an image] {user_message}"})
|
| 100 |
else:
|
| 101 |
+
# --- 3. TEXT ONLY CALL ---
|
| 102 |
history.append({"role": "user", "content": user_message})
|
| 103 |
payload = {"model": TEXT_MODEL, "messages": history, "max_tokens": 1000}
|
| 104 |
resp = requests.post(ROUTER_URL, headers=headers, json=payload)
|
| 105 |
reply = resp.json()["choices"][0]["message"]["content"]
|
| 106 |
|
| 107 |
+
# Save and return
|
| 108 |
history.append({"role": "assistant", "content": reply})
|
| 109 |
doc_ref.set({'messages': history})
|
| 110 |
return jsonify({"reply": reply})
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
+
return jsonify({"error": "Critical Crash", "details": str(e)}), 500
|
| 114 |
|
| 115 |
if __name__ == '__main__':
|
| 116 |
app.run(host='0.0.0.0', port=7860)
|