import os import json from datetime import datetime, timezone from collections import defaultdict from fastapi import FastAPI, HTTPException, Request from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from pydantic import BaseModel, Field from dotenv import load_dotenv from groq import Groq import httpx load_dotenv() app = FastAPI(title="LLM Dictionary", version="1.0.0") # --- Analytics store (in-memory, resets on restart) --- analytics = { "total_lookups": 0, "lookups_by_language": defaultdict(int), "lookups_by_hour": defaultdict(int), "recent_words": [], # last 50 words looked up "top_words": defaultdict(int), "started_at": datetime.now(timezone.utc).isoformat(), } # --- Likes & Comments store (in-memory) --- community = { "likes": 0, "liked_users": set(), # track by session id to prevent duplicates "comments": [], # list of {name, text, time} } GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") HTTP_PROXY = os.getenv("HTTP_PROXY") or os.getenv("http_proxy") or os.getenv("https_proxy") or os.getenv("HTTPS_PROXY") or "" SYSTEM_PROMPT = """You are an expert multilingual dictionary assistant fluent in English, Telugu (తెలుగు), Hindi (हिन्दी), and Sanskrit (संस्कृतम्). When given a word and a target language, provide a comprehensive dictionary entry in that language. Return the following JSON format ONLY (no extra text): { "word": "", "transliteration": "", "language": "", "phonetic": "", "part_of_speech": ["", "", ...], "definitions": [ { "pos": "", "meaning": "", "example": "", "example_translation": "" } ], "synonyms": ["", "", ...], "antonyms": ["", "", ...], "etymology": "", "usage_notes": "" } Rules: - Return ONLY valid JSON, no markdown, no extra text. - Provide at least 2-3 definitions if the word has multiple meanings. - Include real, natural example sentences in the target language. - For Telugu, Hindi, and Sanskrit: write the word, synonyms, antonyms, and examples in native script. - For English lookups: set transliteration and example_translation to null. - If the word is misspelled, correct it and note it in usage_notes. - If the input is not a recognized word in the specified language, return JSON with an \"error\" key explaining why. - If a user enters an English word but selects Telugu/Hindi/Sanskrit, provide the translation and full entry in that language.""" SUPPORTED_LANGUAGES = ["english", "telugu", "hindi", "sanskrit"] class WordQuery(BaseModel): word: str = Field(..., min_length=1, max_length=100) language: str = Field(default="english") api_key: str = Field(default="") class DictionaryResponse(BaseModel): result: dict class CommentInput(BaseModel): name: str = Field(..., min_length=1, max_length=50) text: str = Field(..., min_length=1, max_length=500) session_id: str = Field(default="") class LikeInput(BaseModel): session_id: str = Field(..., min_length=1, max_length=100) @app.post("/api/lookup", response_model=DictionaryResponse) async def lookup_word(query: WordQuery): api_key = query.api_key.strip() or GROQ_API_KEY if not api_key: raise HTTPException( status_code=400, detail="No API key provided. Enter your Groq API key in the settings panel or set GROQ_API_KEY in .env" ) language = query.language.lower().strip() if language not in SUPPORTED_LANGUAGES: raise HTTPException(status_code=400, detail=f"Unsupported language. Choose from: {', '.join(SUPPORTED_LANGUAGES)}") http_client = None if HTTP_PROXY: http_client = httpx.Client(proxy=HTTP_PROXY) client = Groq(api_key=api_key, http_client=http_client, timeout=60.0) try: chat_completion = client.chat.completions.create( messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": f"Look up the word '{query.word}' in {language}. Provide the dictionary entry in {language}."}, ], model="llama-3.3-70b-versatile", temperature=0.1, max_tokens=1024, response_format={"type": "json_object"}, ) raw = chat_completion.choices[0].message.content result = json.loads(raw) # Track analytics now = datetime.now(timezone.utc) analytics["total_lookups"] += 1 analytics["lookups_by_language"][language] += 1 analytics["lookups_by_hour"][now.strftime("%Y-%m-%d %H:00")] += 1 analytics["top_words"][query.word.lower().strip()] += 1 analytics["recent_words"].append({ "word": query.word, "language": language, "time": now.isoformat(), }) analytics["recent_words"] = analytics["recent_words"][-50:] return DictionaryResponse(result=result) except json.JSONDecodeError: raise HTTPException(status_code=502, detail="LLM returned invalid JSON") except Exception as e: error_msg = str(e) if "authentication" in error_msg.lower() or "api key" in error_msg.lower(): raise HTTPException(status_code=401, detail="Invalid Groq API key") raise HTTPException(status_code=502, detail=f"LLM service error: {error_msg}") # --- Analytics API --- @app.get("/api/stats") async def get_stats(): sorted_words = sorted(analytics["top_words"].items(), key=lambda x: -x[1])[:20] sorted_hours = sorted(analytics["lookups_by_hour"].items())[-48:] # last 48 hours return { "total_lookups": analytics["total_lookups"], "started_at": analytics["started_at"], "by_language": dict(analytics["lookups_by_language"]), "top_words": [{"word": w, "count": c} for w, c in sorted_words], "hourly": [{"hour": h, "count": c} for h, c in sorted_hours], "recent": list(reversed(analytics["recent_words"][-20:])), } # --- Like & Comment APIs --- @app.post("/api/like") async def like_app(data: LikeInput): if data.session_id not in community["liked_users"]: community["liked_users"].add(data.session_id) community["likes"] += 1 return {"likes": community["likes"], "liked": True} @app.delete("/api/like") async def unlike_app(data: LikeInput): if data.session_id in community["liked_users"]: community["liked_users"].discard(data.session_id) community["likes"] = max(0, community["likes"] - 1) return {"likes": community["likes"], "liked": False} @app.get("/api/community") async def get_community(session_id: str = ""): return { "likes": community["likes"], "liked": session_id in community["liked_users"], "comments": community["comments"][-50:], "comment_count": len(community["comments"]), } @app.post("/api/comment") async def add_comment(data: CommentInput): comment = { "name": data.name.strip(), "text": data.text.strip(), "time": datetime.now(timezone.utc).isoformat(), } community["comments"].append(comment) community["comments"] = community["comments"][-100:] # keep last 100 return {"comment": comment, "comment_count": len(community["comments"])} @app.get("/stats") async def stats_page(): return FileResponse("static/stats.html") # Serve static frontend app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/") async def root(): return FileResponse("static/index.html")