import os import requests import json import re import io import tempfile from datetime import datetime, timedelta, timezone from bs4 import BeautifulSoup from flask import Flask, request, Response, stream_with_context, render_template_string from supertonic import TTS app = Flask(__name__) # ---------------------------------------------------- # INIT RENDERLIB # ---------------------------------------------------- print("Loading RenderLib...") try: from renderlib import RenderLib renderer = RenderLib() print("RenderLib loaded successfully!") except ImportError as e: print(f"RenderLib not installed yet or error: {e}") renderer = None # ---------------------------------------------------- # INIT TTS MODEL # ---------------------------------------------------- print("Loading Supertonic TTS Model...") try: tts = TTS(auto_download=True) print("TTS Model loaded successfully!") except Exception as e: print(f"Error initializing TTS: {e}") tts = None VOICES = ["M1", "M2", "M3", "M4", "M5", "F1", "F2", "F3", "F4", "F5"] LANGUAGES = { "English": "en", "Korean": "ko", "Japanese": "ja", "Arabic": "ar", "Bulgarian": "bg", "Czech": "cs", "Danish": "da", "German": "de", "Greek": "el", "Spanish": "es", "Estonian": "et", "Finnish": "fi", "French": "fr", "Hindi": "hi", "Croatian": "hr", "Hungarian": "hu", "Indonesian": "id", "Italian": "it", "Lithuanian": "lt", "Latvian": "lv", "Dutch": "nl", "Polish": "pl", "Portuguese": "pt", "Romanian": "ro", "Russian": "ru", "Slovak": "sk", "Slovenian": "sl", "Swedish": "sv", "Turkish": "tr", "Ukrainian": "uk", "Vietnamese": "vi" } VOICE_STYLES_CACHE = {} # ---------------------------------------------------- # HARDCODED MODEL CONFIGURATION (Directly in code) # ---------------------------------------------------- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "") # Secrets se le raha hai # Agar API key bhi hardcode karna ho toh upar wali line ko hata kar yah likhein: # NVIDIA_API_KEY = "your_actual_api_key_here" INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions" MODEL_ID = "mistralai/mistral-small-4-119b-2603" # ---------------------------------------------------- # GPS REVERSE GEOCODING # ---------------------------------------------------- def get_address_from_coords(lat, lon): try: url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}" headers = {'User-Agent': 'CODE_VED_AI_System_by_Divy_Patel'} response = requests.get(url, headers=headers, timeout=5) data = response.json() return data.get('display_name', f"Lat: {lat}, Lon: {lon}") except Exception as e: return f"Lat: {lat}, Lon: {lon}" # ---------------------------------------------------- # SERPAPI GOOGLE SEARCH ENGINE # ---------------------------------------------------- def web_search_scraper(query, num_results=5, user_address=None): results = [] serpapi_key = os.environ.get("SERPAPI_KEY") if not serpapi_key: return results search_query = query if user_address: local_keywords = ["near", "nearby", "distance", "time", "where"] if any(kw in query.lower() for kw in local_keywords): search_query = f"{query} near {user_address}" try: params = {"engine": "google", "q": search_query, "api_key": serpapi_key, "num": num_results, "hl": "en", "gl": "in"} response = requests.get("https://serpapi.com/search", params=params, timeout=10) data = response.json() if "organic_results" in data: for item in data["organic_results"]: title = item.get("title", "") link = item.get("link", "") snippet = item.get("snippet", "") if title and snippet: results.append({"title": title, "link": link, "snippet": snippet}) except Exception: pass return results # ---------------------------------------------------- # RSS TECH NEWS SCRAPER # ---------------------------------------------------- def get_live_web_data(query): url = f"https://news.google.com/rss/search?q={query}&hl=en&gl=IN&ceid=IN:en" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"} tech_keywords = ["ai", "artificial intelligence", "smartphone", "mobile", "feature", "whatsapp", "google", "tech", "technology", "gadget", "apple", "nasa"] block_keywords = ["share news", "stock"] scraped_results = [] try: response = requests.get(url, headers=headers, timeout=6) if response.status_code == 200: soup = BeautifulSoup(response.text, "html.parser") items = soup.find_all('item') for item in items: title = item.title.text if item.title else "No Title" title_lower = title.lower() if any(b_kw in title_lower for b_kw in block_keywords): continue if any(t_kw in title_lower for t_kw in tech_keywords): link = item.link.text if item.link else "#" pub_date = item.pubdate.text if item.pubdate else "" source = item.source.text if item.source else "Google News" scraped_results.append({ "title": title, "snippet": f"Published: {pub_date} | Source: {source}", "link": link }) if len(scraped_results) >= 5: break except Exception: pass return scraped_results # ---------------------------------------------------- # HOME ROUTE # ---------------------------------------------------- @app.route('/') def home(): try: with open('index.html', 'r', encoding='utf-8') as f: return render_template_string(f.read()) except Exception as e: return f"
index.html missing: {str(e)}
" # ---------------------------------------------------- # RENDERLIB API ENDPOINT # ---------------------------------------------------- @app.route('/api/render', methods=['POST']) def render_content(): if renderer is None: return Response(json.dumps({"error": "RenderLib is not available on the server."}), status=500, mimetype='application/json') data = request.get_json() or {} subject = data.get("subject", "math") method = data.get("method", "to_latex") args = data.get("args", []) kwargs = data.get("kwargs", {}) expression = data.get("expression") if expression and not args: args = [expression] try: result = renderer.render(subject, method, *args, **kwargs) return Response(json.dumps({"result": result}), mimetype='application/json') except Exception as e: return Response(json.dumps({"error": f"RenderLib Error: {str(e)}"}), status=500, mimetype='application/json') # ---------------------------------------------------- # CHAT API ENDPOINT (Hardcoded Model & URL) # ---------------------------------------------------- @app.route('/api/chat', methods=['POST']) def chat(): if not NVIDIA_API_KEY: return Response(json.dumps({"error": "Configuration Error: NVIDIA_API_KEY is missing."}), mimetype='application/json', status=500) data = request.get_json() or {} user_message = data.get("message", "") attachments = data.get("attachments", []) is_search = data.get("is_search", False) history = data.get("history", []) location = data.get("location") user_address = None max_tokens = data.get("max_tokens", 4096) ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30) current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST") thinking_mode = data.get("thinking_mode", False) thinking_effort = data.get("thinking_effort", "medium") thinking_instruction = "" if thinking_mode: thinking_instruction = f"\n[CRITICAL INSTRUCTION: THINKING MODE ENABLED - Effort: {thinking_effort}]\nYou MUST format your reasoning exactly inside