Spaces:
Sleeping
Sleeping
| import os | |
| import sys | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel | |
| import uvicorn | |
| from google import generativeai as genai | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv() | |
| # Configure Google API | |
| api_key = os.getenv("HF_GOOGLE_API_KEY") or os.getenv("GOOGLE_API_KEY") | |
| if not api_key: | |
| raise ValueError("Google API key not found. Please set HF_GOOGLE_API_KEY in Hugging Face Spaces secrets or GOOGLE_API_KEY in .env file.") | |
| try: | |
| genai.configure(api_key=api_key) | |
| except Exception as e: | |
| print(f"Error configuring Generative AI: {str(e)}") | |
| raise | |
| # Global chat sessions dictionary to maintain sessions between requests | |
| chat_sessions = {} | |
| def get_chat_session(session_id): | |
| """Get an existing chat session or create a new one.""" | |
| if session_id not in chat_sessions: | |
| try: | |
| model = genai.GenerativeModel('gemini-3-flash-preview') | |
| chat_sessions[session_id] = model.start_chat(history=[]) | |
| except Exception as e: | |
| raise Exception(f"Failed to create chat session: {str(e)}") | |
| return chat_sessions[session_id] | |
| # FastAPI App Setup | |
| app = FastAPI(title="ChatBot Pro Premium API") | |
| # Add CORS middleware | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| class ChatRequest(BaseModel): | |
| message: str | |
| session_id: str = "default" | |
| class ChatResponse(BaseModel): | |
| response: str | |
| async def chat_endpoint(request: ChatRequest): | |
| if not request.message or not request.message.strip(): | |
| raise HTTPException(status_code=400, detail="Message cannot be empty") | |
| try: | |
| chat = get_chat_session(request.session_id) | |
| response = chat.send_message(request.message) | |
| return ChatResponse(response=response.text) | |
| except Exception as e: | |
| print(f"Error in chat endpoint: {str(e)}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def clear_chat(session_id: str): | |
| if session_id in chat_sessions: | |
| del chat_sessions[session_id] | |
| return {"status": "success", "message": "Chat history cleared"} | |
| # Mount static files | |
| static_dir = os.path.join(os.path.dirname(__file__), "static") | |
| if not os.path.exists(static_dir): | |
| os.makedirs(static_dir) | |
| app.mount("/static", StaticFiles(directory=static_dir), name="static") | |
| async def read_index(): | |
| return FileResponse(os.path.join(static_dir, "index.html")) | |
| if __name__ == "__main__": | |
| print("Starting ChatBot Pro Premium on http://127.0.0.1:8000") | |
| uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True) |