Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
@@ -1,31 +1,93 @@
|
|
|
|
|
|
|
|
1 |
from hugchat import hugchat
|
2 |
from hugchat.login import Login
|
3 |
-
import
|
4 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
app = FastAPI()
|
6 |
-
|
|
|
|
|
7 |
EMAIL = "[email protected]"
|
8 |
PASSWORD = "Allahisgreatest17"
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
14 |
|
15 |
-
|
16 |
-
|
|
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
return response
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
|
|
|
|
|
|
30 |
|
|
|
|
|
|
|
|
|
|
|
31 |
|
|
|
1 |
+
import os
|
2 |
+
from fastapi import FastAPI, HTTPException
|
3 |
+
from pydantic import BaseModel
|
4 |
from hugchat import hugchat
|
5 |
from hugchat.login import Login
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
from contextlib import asynccontextmanager
|
8 |
+
import logging
|
9 |
+
|
10 |
+
# Set up logging
|
11 |
+
logging.basicConfig(level=logging.INFO)
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
# Load environment variables
|
15 |
+
load_dotenv()
|
16 |
+
|
17 |
+
# Initialize FastAPI app
|
18 |
app = FastAPI()
|
19 |
+
|
20 |
+
# HuggingFace credentials from environment variables
|
21 |
+
# HuggingFace credentials from environment variables
|
22 |
EMAIL = "[email protected]"
|
23 |
PASSWORD = "Allahisgreatest17"
|
24 |
+
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e"
|
25 |
+
|
26 |
+
# Cookie directory path
|
27 |
+
COOKIE_PATH_DIR = "./cookies/"
|
28 |
+
|
29 |
+
# Global chatbot instance
|
30 |
+
chatbot = None
|
31 |
|
32 |
+
# Pydantic model for request body
|
33 |
+
class PromptRequest(BaseModel):
|
34 |
+
prompt: str
|
35 |
|
36 |
+
# Ensure cookie directory exists
|
37 |
+
def ensure_cookie_directory():
|
38 |
+
if not os.path.exists(COOKIE_PATH_DIR):
|
39 |
+
os.makedirs(COOKIE_PATH_DIR)
|
40 |
+
logger.info("Created cookie directory: %s", COOKIE_PATH_DIR)
|
41 |
|
42 |
+
# Lifespan handler for startup and shutdown
|
43 |
+
@asynccontextmanager
|
44 |
+
async def lifespan(app: FastAPI):
|
45 |
+
# Startup: Initialize chatbot
|
46 |
+
global chatbot
|
47 |
+
try:
|
48 |
+
# Validate credentials
|
49 |
+
if not EMAIL or not PASSWORD or not ASSISTANT_ID:
|
50 |
+
raise ValueError("HuggingFace credentials or assistant ID not provided in environment variables")
|
51 |
|
52 |
+
# Ensure cookie directory exists
|
53 |
+
ensure_cookie_directory()
|
|
|
54 |
|
55 |
+
# Log in to HuggingFace
|
56 |
+
sign = Login(EMAIL, PASSWORD)
|
57 |
+
cookies = sign.login(cookie_path_dir=COOKIE_PATH_DIR, save_cookies=True)
|
58 |
+
logger.info("Successfully logged in to HuggingFace")
|
59 |
+
|
60 |
+
# Initialize chatbot
|
61 |
+
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
|
62 |
+
# Start a new conversation
|
63 |
+
chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
|
64 |
+
logger.info("Chatbot initialized with assistant ID: %s", ASSISTANT_ID)
|
65 |
+
except Exception as e:
|
66 |
+
logger.error("Failed to initialize chatbot: %s", str(e))
|
67 |
+
raise HTTPException(status_code=500, detail="Failed to initialize chatbot")
|
68 |
+
|
69 |
+
yield # Application runs here
|
70 |
+
|
71 |
+
# Shutdown: Clean up (optional)
|
72 |
+
logger.info("Shutting down application")
|
73 |
+
|
74 |
+
# Attach lifespan handler to FastAPI app
|
75 |
+
app.lifespan = lifespan
|
76 |
+
|
77 |
+
# Endpoint to handle chat requests
|
78 |
+
@app.post("/ask")
|
79 |
+
async def ask(prompt_request: PromptRequest):
|
80 |
+
try:
|
81 |
+
if not chatbot:
|
82 |
+
raise HTTPException(status_code=500, detail="Chatbot not initialized")
|
83 |
|
84 |
+
# Send prompt to chatbot
|
85 |
+
response = chatbot.chat(prompt_request.prompt, stream=False)
|
86 |
+
logger.info("Received response for prompt: %s", prompt_request.prompt)
|
87 |
|
88 |
+
# Return structured response
|
89 |
+
return {"status": "success", "response": response}
|
90 |
+
except Exception as e:
|
91 |
+
logger.error("Error processing request: %s", str(e))
|
92 |
+
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
93 |
|