Spaces:
Runtime error
Runtime error
import os | |
from datetime import datetime | |
from supabase import create_client, Client | |
import requests | |
SUPABASE_URL = os.getenv("SUPABASE_URL") | |
SUPABASE_KEY = os.getenv("SUPABASE_KEY") | |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) | |
def get_geo_location(ip: str) -> str: | |
""" | |
Fetch approximate geo-location for the given IP address. | |
Returns 'Unknown' if lookup fails. | |
""" | |
try: | |
if ip.startswith("127.") or ip == "localhost": | |
return "Localhost" | |
resp = requests.get(f"https://ipapi.co/{ip}/country_name/", timeout=3) | |
if resp.status_code == 200: | |
return resp.text.strip() or "Unknown" | |
except Exception: | |
pass | |
return "Unknown" | |
def log_query(document_source: str, question: str, answer: str, | |
ip_address: str, response_time: float, | |
user_agent: str = None): | |
""" | |
Store a question-answer log in Supabase with geo-location and user-agent. | |
""" | |
now_str = datetime.utcnow().isoformat() | |
geo_location = get_geo_location(ip_address) | |
try: | |
supabase.table("qa_logs").insert({ | |
"document_source": document_source, | |
"question": question, | |
"answer": answer, | |
"ip_address": ip_address, | |
"geo_location": geo_location, | |
"user_agent": user_agent or "Unknown", | |
"response_time_sec": round(response_time, 2), | |
"created_at": now_str | |
}).execute() | |
except Exception as e: | |
print(f"Failed to log query to Supabase: {e}") | |