TS447 commited on
Commit
1a9f910
·
verified ·
1 Parent(s): 898e3a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -43
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
@@ -9,85 +10,84 @@ app = Flask(__name__)
9
  CORS(app)
10
 
11
  # --- FIREBASE SETUP ---
12
- cred = credentials.Certificate("firebase_key.json")
13
- firebase_admin.initialize_app(cred)
14
- db = firestore.client()
 
 
 
 
15
 
16
- # --- SECRETS ---
17
  HF_TOKEN = os.environ.get("HF_TOKEN")
18
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
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 = "meta-llama/llama-4-scout-17b-16e-instruct"
25
 
26
  @app.route('/', methods=['GET'])
27
  def home():
28
- return jsonify({"status": "TS AI Brain (Debug Mode) is Live! 🔥"})
29
 
30
  @app.route('/api/chat', methods=['POST'])
31
  def chat():
32
- is_form_data = 'multipart/form-data' in request.content_type if request.content_type else False
33
- user_message = ""
34
- image_url = None
 
 
35
 
36
- if is_form_data or request.files:
37
- user_message = request.form.get("message", "What is in this image?")
38
- image_file = request.files.get("image")
39
- if image_file:
40
- # 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}
44
- try:
45
  tg_resp = requests.post(tg_url, data=data, files=files).json()
 
46
  if tg_resp.get('ok'):
47
  file_id = tg_resp['result']['photo'][-1]['file_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
- else:
51
- return jsonify({"error": "Telegram error", "details": tg_resp}), 500
52
- except Exception as e:
53
- return jsonify({"error": "Telegram Crash", "details": str(e)}), 500
54
-
55
- else:
56
- user_message = request.json.get("message", "")
57
 
58
- # LOAD HISTORY
59
- doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
60
- doc = doc_ref.get()
61
- history = doc.to_dict().get('messages', []) if doc.exists else [{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}]
62
 
63
- try:
64
  if image_url:
65
- # --- VISION CALL VIA GROQ ---
66
  groq_url = "https://api.groq.com/openai/v1/chat/completions"
67
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
68
  payload = {
69
  "model": VISION_MODEL,
70
  "messages": [{"role": "user", "content": [{"type": "text", "text": user_message}, {"type": "image_url", "image_url": {"url": image_url}}]}],
 
71
  }
72
- resp = requests.post(groq_url, headers=headers, json=payload)
73
- result = resp.json()
74
 
75
- # AGAR RESPONSE MEIN ERROR HAI TOH BATAYO
76
- if "choices" in result:
77
- reply = result["choices"]["message"]["content"]
78
  else:
79
- return jsonify({"error": "Groq ne mana kar diya!", "raw_response": result}), 500
80
-
81
- history.append({"role": "user", "content": f"[Screenshot] {user_message}"})
82
  else:
83
- # --- TEXT CALL VIA HUGGING FACE ---
84
  history.append({"role": "user", "content": user_message})
85
  hf_url = "https://router.huggingface.co/v1/chat/completions"
86
  headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
87
  payload = {"model": TEXT_MODEL, "messages": history}
88
- resp = requests.post(hf_url, headers=headers, json=payload)
89
- reply = resp.json()["choices"][0]["message"]["content"]
90
 
 
91
  history.append({"role": "assistant", "content": reply})
92
  doc_ref.set({'messages': history})
93
  return jsonify({"reply": reply})
 
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
 
10
  CORS(app)
11
 
12
  # --- FIREBASE SETUP ---
13
+ try:
14
+ if not firebase_admin._apps:
15
+ cred = credentials.Certificate("firebase_key.json")
16
+ firebase_admin.initialize_app(cred)
17
+ db = firestore.client()
18
+ except Exception as e:
19
+ print(f"Firebase Error: {e}")
20
 
21
+ # --- SECRETS (Tijori) ---
22
  HF_TOKEN = os.environ.get("HF_TOKEN")
23
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
24
  TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
25
  TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
26
 
27
+ # 2026 CURRENT MODELS
28
  TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
29
+ VISION_MODEL = "meta-llama/llama-4-scout-17b-16e-instruct" # March 2026 Stable
30
 
31
  @app.route('/', methods=['GET'])
32
  def home():
33
+ return jsonify({"status": "TS AI Brain (Bulletproof 2026) is Active! 🚀"})
34
 
35
  @app.route('/api/chat', methods=['POST'])
36
  def chat():
37
+ try:
38
+ # 1. PATA LAGAO REQUEST KYA HAI
39
+ is_form_data = 'multipart/form-data' in request.content_type if request.content_type else False
40
+ user_message = ""
41
+ image_url = None
42
 
43
+ if is_form_data:
44
+ user_message = request.form.get("message", "Analyze this.")
45
+ if 'image' in request.files:
46
+ image_file = request.files['image']
47
+ # --- TELEGRAM GODOWN UPLOAD ---
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}
 
51
  tg_resp = requests.post(tg_url, data=data, files=files).json()
52
+
53
  if tg_resp.get('ok'):
54
  file_id = tg_resp['result']['photo'][-1]['file_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
+ else:
58
+ data = request.get_json(silent=True) or {}
59
+ user_message = data.get("message", "")
 
 
 
 
60
 
61
+ # 2. LOAD HISTORY
62
+ doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
63
+ doc = doc_ref.get()
64
+ history = doc.to_dict().get('messages', []) if doc.exists else [{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}]
65
 
66
+ # 3. VISION CALL (GROQ) OR TEXT CALL (HF)
67
  if image_url:
 
68
  groq_url = "https://api.groq.com/openai/v1/chat/completions"
69
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
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": 1024
74
  }
75
+ resp = requests.post(groq_url, headers=headers, json=payload).json()
 
76
 
77
+ # SAFE RESPONSE PARSING
78
+ if isinstance(resp, dict) and "choices" in resp:
79
+ reply = resp["choices"]["message"]["content"]
80
  else:
81
+ return jsonify({"error": "Groq API ne error diya", "raw": resp}), 500
 
 
82
  else:
 
83
  history.append({"role": "user", "content": user_message})
84
  hf_url = "https://router.huggingface.co/v1/chat/completions"
85
  headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
86
  payload = {"model": TEXT_MODEL, "messages": history}
87
+ resp = requests.post(hf_url, headers=headers, json=payload).json()
88
+ reply = resp["choices"][0]["message"]["content"]
89
 
90
+ # 4. SAVE & REPLY
91
  history.append({"role": "assistant", "content": reply})
92
  doc_ref.set({'messages': history})
93
  return jsonify({"reply": reply})