import os import requests import json from datetime import datetime, timedelta, timezone from bs4 import BeautifulSoup from flask import Flask, request, Response, stream_with_context, render_template_string app = Flask(__name__) # ---------------------------------------------------- # 📍 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: print(f"Geocoding Error: {e}") return f"Lat: {lat}, Lon: {lon}" # ---------------------------------------------------- # 🌐 SERPAPI GOOGLE SEARCH ENGINE (Location Aware) # ---------------------------------------------------- def web_search_scraper(query, num_results=5, user_address=None): results = [] serpapi_key = os.environ.get("SERPAPI_KEY") if not serpapi_key: print("ALERT: SERPAPI_KEY missing in secrets.") 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 as e: print(f"SerpApi Error: {e}") return results # ---------------------------------------------------- # 📰 RSS TECH NEWS SCRAPER (Pure Tech Filter) # ---------------------------------------------------- def get_live_web_data(query): print(f"[Live Feed] Fetching news for topic: '{query}'...") url = f"https://news.google.com/rss/search?q={query}&hl=hi&gl=IN&ceid=IN:hi" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"} tech_keywords = [ "ai", "artificial intelligence", "एआई", "इंटेलिजेंस", "स्मार्टफोन", "smartphone", "mobile", "मोबाइल", "फीचर", "feature", "whatsapp", "google", "tech", "तकनीक", "टेक्नोलॉजी", "गैजेट", "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"प्रकाशित तिथि: {pub_date} | स्रोत: {source}", "link": link }) if len(scraped_results) >= 5: break except Exception as e: print(f"[Live Feed Error] Failed to fetch: {e}") return scraped_results # ---------------------------------------------------- @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)}
" @app.route('/api/chat', methods=['POST']) def chat(): # 🔐 SECURE ENVIRONMENT VARIABLES API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY") INVOKE_URL = os.environ.get("BASE_URL") MODEL_ID = os.environ.get("MODEL_ID") if not API_KEY or not INVOKE_URL or not MODEL_ID: return Response("Server Error: Critical configuration secrets missing.", 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) temperature = 1.00 top_p = 0.95 thinking_mode = data.get("thinking_mode", False) thinking_effort = data.get("thinking_effort", "medium") ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30) current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST") # 🔥 DYNAMIC THINKING INSTRUCTIONS thinking_instruction = "" if thinking_mode: if thinking_effort == "low": effort_text = "Keep your reasoning brief, direct, and fast." elif thinking_effort == "high": effort_text = "Perform a deep, exhaustive, and highly detailed multi-step analysis." else: effort_text = "Perform a standard, balanced step-by-step logical reasoning process." thinking_instruction = f""" [CRITICAL INSTRUCTION: THINKING MODE ENABLED] Effort Level: {thinking_effort.upper()} - {effort_text} You MUST format your reasoning exactly inside