Vedika commited on
Commit
41bd13c
·
verified ·
1 Parent(s): 2fd8500

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -38
app.py CHANGED
@@ -1,52 +1,97 @@
1
  import os
2
- import logging
3
- import time
4
- from flask import Flask, request, Response, stream_with_context, jsonify, send_from_directory
5
 
6
- # --- 1. एन्टरप्राइज लॉगिंग कॉन्फ़िगरेशन ---
7
- logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s: %(message)s')
8
- logger = logging.getLogger("ArjunCore")
9
 
10
- app = Flask(__name__, static_folder='.', static_url_path='')
 
 
 
11
 
12
- # --- 2.ॉनफ़िरेक्ल (Environment variables से ेने लिए) ---
13
- class Config:
14
- API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
15
- ENDPOINT = os.environ.get("BASE_URL")
16
- MODEL_ID = os.environ.get("MODEL_ID")
 
 
17
 
18
- # --- 3. रूट: सर्वर रन होते ही ट्रिगर होना ---
19
  @app.route('/')
20
- def index():
21
- """यह फंक्शन सुनिश्चित करता है कि जैसे ही यूज़र सर्वर पर आए, index.html लोड हो जाए।"""
22
- logger.info("Serving index.html interface...")
23
- return send_from_directory('.', 'index.html')
 
 
 
24
 
25
- # --- 4. चैट एपीआई (LLM Proxy) ---
26
  @app.route('/api/chat', methods=['POST'])
27
  def chat():
28
- """फ्रंटएंड (Gradio/JS) से आनवाली रिक्वेस्ट को LLM तक पुँचना।"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  try:
30
- data = request.json
31
- # यहाँ आप PayloadBuilder का उपयोग करके अपना लॉजिक बढ़ा सकते हैं
32
- logger.info("Processing chat request...")
33
 
34
- # प्रॉक्सी लॉजिक यहाँ डालें (जैसे पिछला कोड था)
35
- return jsonify({"status": "processing", "message": "Backend connected successfully"})
 
 
 
 
 
 
36
  except Exception as e:
37
- return jsonify({"error": str(e)}), 500
38
-
39
- # --- 5. हेल्थ चेक ---
40
- @app.route('/health')
41
- def health():
42
- return jsonify({"status": "Arjun Core Active", "uptime": time.time()})
43
 
44
- # --- 6. मुख्य एक्जीक्यूशन ---
45
  if __name__ == '__main__':
46
- port = int(os.environ.get("PORT", 7860))
47
- print("\n==============================================")
48
- print(" ARJUN CORE V3 - SYSTEM ONLINE ")
49
- print("==============================================\n")
50
-
51
- # यह Flask का सर्वर सीधे index.html को सर्व करेगा
52
- app.run(host='0.0.0.0', port=port, threaded=True)
 
1
  import os
2
+ import requests
3
+ from flask import Flask, request, Response, stream_with_context, render_template_string
 
4
 
5
+ app = Flask(__name__)
 
 
6
 
7
+ # 🔐 100% सुरक्षित: सब कुछ केवल 'Secrets' से कॉल होगा, कोई हार्डकोडेड डेटा नहीं।
8
+ API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
9
+ BASE_URL = os.environ.get("BASE_URL")
10
+ MODEL_ID = os.environ.get("MODEL_ID")
11
 
12
+ # URL को सुरक्िूप साना कि कोईिफ़ॉल्ट लिं दिखे
13
+ INVOKE_URL = ""
14
+ if BASE_URL:
15
+ if not BASE_URL.endswith("/chat/completions"):
16
+ INVOKE_URL = f"{BASE_URL.rstrip('/')}/chat/completions"
17
+ else:
18
+ INVOKE_URL = BASE_URL
19
 
 
20
  @app.route('/')
21
+ def home():
22
+ try:
23
+ with open('index.html', 'r', encoding='utf-8') as f:
24
+ html_content = f.read()
25
+ return render_template_string(html_content)
26
+ except Exception as e:
27
+ return f"index.html file missing! Error: {str(e)}"
28
 
 
29
  @app.route('/api/chat', methods=['POST'])
30
  def chat():
31
+ # सुक्षा जाच: अगरीक्रट्स नह हैं, तो रिक्वेस्ट आगे ीं जएगी
32
+ if not API_KEY or not INVOKE_URL or not MODEL_ID:
33
+ return Response("Server Error: Configuration secrets are missing.", status=500)
34
+
35
+ data = request.get_json() or {}
36
+ user_message = data.get("message", "")
37
+ attachments = data.get("attachments", [])
38
+ system_prompt = data.get("system_prompt", "")
39
+ max_tokens = data.get("max_tokens", 4096)
40
+ temperature = data.get("temperature", 0.6)
41
+
42
+ messages = []
43
+
44
+ # 1. सिस्टम प्रॉम्प्ट
45
+ if system_prompt.strip():
46
+ messages.append({"role": "system", "content": system_prompt})
47
+
48
+ # 2. मल्टीमोडल इनपुट
49
+ content_payload = []
50
+ if user_message.strip():
51
+ content_payload.append({"type": "text", "text": user_message})
52
+
53
+ for att in attachments:
54
+ att_type = att.get("type")
55
+ b64_data = att.get("data")
56
+
57
+ if att_type == "image":
58
+ content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
59
+ elif att_type in ["audio", "file"]:
60
+ content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
61
+
62
+ if not content_payload:
63
+ content_payload.append({"type": "text", "text": "Hello"})
64
+
65
+ messages.append({"role": "user", "content": content_payload})
66
+
67
+ headers = {
68
+ "Authorization": f"Bearer {API_KEY}",
69
+ "Accept": "text/event-stream"
70
+ }
71
+
72
+ payload = {
73
+ "model": MODEL_ID,
74
+ "messages": messages,
75
+ "max_tokens": int(max_tokens),
76
+ "temperature": float(temperature),
77
+ "top_p": 0.70,
78
+ "stream": True
79
+ }
80
+
81
  try:
82
+ # सुरक्षित स्ट्रीमिंग रिक्वेस्ट
83
+ response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
 
84
 
85
+ def generate():
86
+ for line in response.iter_lines():
87
+ if line:
88
+ decoded_line = line.decode("utf-8")
89
+ if decoded_line.startswith("data: "):
90
+ yield decoded_line + "\n\n"
91
+
92
+ return Response(stream_with_context(generate()), mimetype='text/event-stream')
93
  except Exception as e:
94
+ return Response("Internal Error: Unable to process request securely.", status=500)
 
 
 
 
 
95
 
 
96
  if __name__ == '__main__':
97
+ app.run(host='0.0.0.0', port=7860)