TS447 commited on
Commit
16a1744
·
verified ·
1 Parent(s): 33d039b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -24
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import requests
 
3
  from flask import Flask, request, jsonify
4
  from flask_cors import CORS
5
  import firebase_admin
@@ -8,28 +9,23 @@ from firebase_admin import credentials, firestore
8
  app = Flask(__name__)
9
  CORS(app)
10
 
11
-
12
  cred = credentials.Certificate("firebase_key.json")
13
  firebase_admin.initialize_app(cred)
14
  db = firestore.client()
15
 
16
-
17
  HF_TOKEN = os.environ.get("HF_TOKEN")
18
  TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
19
  TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
20
 
21
-
22
  TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
23
- VISION_MODEL = "meta-llama/Llama-3.2-11B-Vision-Instruct"
24
-
25
-
26
- ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
27
-
28
- VISION_API_URL = f"https://api-inference.huggingface.co/models/{VISION_MODEL}/v1/chat/completions"
29
 
30
  @app.route('/', methods=['GET'])
31
  def home():
32
- return jsonify({"status": "TS AI Brain (Direct Vision Access) is Active! 🔥"})
33
 
34
  @app.route('/api/chat', methods=['POST'])
35
  def chat():
@@ -38,10 +34,10 @@ def chat():
38
  image_url = None
39
 
40
  if is_form_data or request.files:
41
- user_message = request.form.get("message", "Is photo ko dekho.")
42
  image_file = request.files.get("image")
43
  if image_file:
44
-
45
  tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto"
46
  files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)}
47
  data = {'chat_id': TG_CHAT_ID}
@@ -52,43 +48,56 @@ def chat():
52
  file_info = requests.get(f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}").json()
53
  image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
54
  except Exception as e:
55
- return jsonify({"error": "Telegram Fail", "details": str(e)}), 500
56
  else:
57
  data = request.json
58
  user_message = data.get("message", "")
59
 
60
- # History Load
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 = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
66
 
67
  try:
68
  if image_url:
69
-
70
  payload = {
71
  "model": VISION_MODEL,
72
  "messages": [{"role": "user", "content": [{"type": "text", "text": user_message}, {"type": "image_url", "image_url": {"url": image_url}}]}],
73
- "max_tokens": 500
74
  }
 
 
 
75
 
76
- response = requests.post(VISION_API_URL, headers=headers, json=payload)
77
- reply = response.json()["choices"]["message"]["content"]
78
- history.append({"role": "user", "content": f"[Photo Sent] {user_message}"})
79
- else:
 
 
 
 
 
 
80
 
 
 
 
81
  history.append({"role": "user", "content": user_message})
82
  payload = {"model": TEXT_MODEL, "messages": history, "max_tokens": 1000}
83
- response = requests.post(ROUTER_URL, headers=headers, json=payload)
84
- reply = response.json()["choices"][0]["message"]["content"]
 
85
 
86
  history.append({"role": "assistant", "content": reply})
87
  doc_ref.set({'messages': history})
88
  return jsonify({"reply": reply})
89
 
90
  except Exception as e:
91
- return jsonify({"error": "API Error", "details": str(e)}), 500
92
 
93
  if __name__ == '__main__':
94
  app.run(host='0.0.0.0', port=7860)
 
1
  import os
2
  import requests
3
+ import time
4
  from flask import Flask, request, jsonify
5
  from flask_cors import CORS
6
  import firebase_admin
 
9
  app = Flask(__name__)
10
  CORS(app)
11
 
12
+ # --- FIREBASE SETUP ---
13
  cred = credentials.Certificate("firebase_key.json")
14
  firebase_admin.initialize_app(cred)
15
  db = firestore.client()
16
 
17
+ # --- SECRETS ---
18
  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
+ VISION_MODEL = "Qwen/Qwen2-VL-7B-Instruct" # Sabse fast vision model
 
 
 
 
 
25
 
26
  @app.route('/', methods=['GET'])
27
  def home():
28
+ return jsonify({"status": "TS AI Brain (Final Debug Mode) is Active! 🔥"})
29
 
30
  @app.route('/api/chat', methods=['POST'])
31
  def chat():
 
34
  image_url = None
35
 
36
  if is_form_data or request.files:
37
+ user_message = request.form.get("message", "Is photo ko read karo.")
38
  image_file = request.files.get("image")
39
  if image_file:
40
+ # 1. TELEGRAM UPLOAD
41
  tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto"
42
  files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)}
43
  data = {'chat_id': TG_CHAT_ID}
 
48
  file_info = requests.get(f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}").json()
49
  image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
50
  except Exception as e:
51
+ return jsonify({"error": "Telegram upload fail", "details": str(e)}), 500
52
  else:
53
  data = request.json
54
  user_message = data.get("message", "")
55
 
56
+ # LOAD HISTORY
57
  doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
58
  doc = doc_ref.get()
59
+ history = doc.to_dict().get('messages', []) if doc.exists else [{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}]
60
 
61
  headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
62
 
63
  try:
64
  if image_url:
65
+ # 2. VISION API CALL (Direct Model Path)
66
  payload = {
67
  "model": VISION_MODEL,
68
  "messages": [{"role": "user", "content": [{"type": "text", "text": user_message}, {"type": "image_url", "image_url": {"url": image_url}}]}],
69
+ "max_tokens": 1000
70
  }
71
+ # Direct Inference URL for Vision
72
+ V_URL = f"https://api-inference.huggingface.co/models/{VISION_MODEL}/v1/chat/completions"
73
+ resp = requests.post(V_URL, headers=headers, json=payload)
74
 
75
+ # Agar model load ho raha ho (503), toh thoda wait karke dobara try karein
76
+ if resp.status_code == 503:
77
+ time.sleep(5)
78
+ resp = requests.post(V_URL, headers=headers, json=payload)
79
+
80
+ result = resp.json()
81
+ if "choices" in result:
82
+ reply = result["choices"][0]["message"]["content"].strip()
83
+ else:
84
+ return jsonify({"error": "Vision Model ne sahi jawab nahi diya", "api_response": result}), 500
85
 
86
+ history.append({"role": "user", "content": f"[Screenshot Sent] {user_message}"})
87
+ else:
88
+ # 3. TEXT API CALL
89
  history.append({"role": "user", "content": user_message})
90
  payload = {"model": TEXT_MODEL, "messages": history, "max_tokens": 1000}
91
+ T_URL = "https://router.huggingface.co/v1/chat/completions"
92
+ resp = requests.post(T_URL, headers=headers, json=payload)
93
+ reply = resp.json()["choices"]["message"]["content"].strip()
94
 
95
  history.append({"role": "assistant", "content": reply})
96
  doc_ref.set({'messages': history})
97
  return jsonify({"reply": reply})
98
 
99
  except Exception as e:
100
+ return jsonify({"error": "System Crash!", "details": str(e)}), 500
101
 
102
  if __name__ == '__main__':
103
  app.run(host='0.0.0.0', port=7860)