Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,126 +1,31 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from fastapi.responses import StreamingResponse
|
| 3 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
-
from pydantic import BaseModel
|
| 5 |
from hugchat import hugchat
|
| 6 |
from hugchat.login import Login
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
# Set up logging
|
| 11 |
-
logging.basicConfig(level=logging.INFO)
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
allow_origins=["*"],
|
| 20 |
-
allow_methods=["*"],
|
| 21 |
-
allow_headers=["*"],
|
| 22 |
-
)
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
question: str
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
-
def setup_chatbot(email, password, cookie_path, assistant_id):
|
| 32 |
-
"""
|
| 33 |
-
Sets up the Hugging Face chatbot with login and conversation.
|
| 34 |
-
|
| 35 |
-
Args:
|
| 36 |
-
email (str): User email for login
|
| 37 |
-
password (str): User password for login
|
| 38 |
-
cookie_path (str): Directory to store cookies
|
| 39 |
-
assistant_id (str): ID of the assistant to use
|
| 40 |
-
|
| 41 |
-
Returns:
|
| 42 |
-
hugchat.ChatBot: Configured chatbot instance
|
| 43 |
-
"""
|
| 44 |
-
try:
|
| 45 |
-
logger.info("Setting up chatbot...")
|
| 46 |
-
# Create cookie directory if it doesn't exist
|
| 47 |
-
os.makedirs(cookie_path, exist_ok=True)
|
| 48 |
-
|
| 49 |
-
logger.info("Logging in with Hugging Face credentials...")
|
| 50 |
-
sign = Login(email, password)
|
| 51 |
-
cookies = sign.login(cookie_dir_path=cookie_path, save_cookies=True)
|
| 52 |
-
|
| 53 |
-
logger.info("Initializing ChatBot...")
|
| 54 |
-
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
|
| 55 |
-
|
| 56 |
-
logger.info(f"Creating new conversation with assistant ID: {assistant_id}")
|
| 57 |
-
chatbot.new_conversation(assistant=assistant_id, switch_to=True)
|
| 58 |
-
logger.info("Chatbot setup complete.")
|
| 59 |
-
return chatbot
|
| 60 |
-
except Exception as e:
|
| 61 |
-
logger.error(f"Failed to set up chatbot: {str(e)}")
|
| 62 |
-
raise Exception(f"Failed to set up chatbot: {e}")
|
| 63 |
|
| 64 |
-
# Initialize chatbot at startup
|
| 65 |
-
@app.on_event("startup")
|
| 66 |
-
async def startup_event():
|
| 67 |
-
global chatbot
|
| 68 |
-
# Credentials and configuration
|
| 69 |
-
EMAIL = os.getenv("EMAIL")
|
| 70 |
-
PASSWD = os.getenv("PASSWD")
|
| 71 |
-
COOKIE_PATH_DIR = "./cookies/"
|
| 72 |
-
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e" # Replace with your actual assistant ID
|
| 73 |
-
|
| 74 |
-
try:
|
| 75 |
-
chatbot = setup_chatbot(EMAIL, PASSWD, COOKIE_PATH_DIR, ASSISTANT_ID)
|
| 76 |
-
except Exception as e:
|
| 77 |
-
logger.error(f"Startup error: {str(e)}")
|
| 78 |
|
| 79 |
-
@app.post("/generate")
|
| 80 |
-
async def generate_response(request: QuestionRequest):
|
| 81 |
-
"""
|
| 82 |
-
Generates a streaming response from the AI based on the provided question.
|
| 83 |
-
|
| 84 |
-
Args:
|
| 85 |
-
request (QuestionRequest): JSON body containing the question.
|
| 86 |
-
|
| 87 |
-
Returns:
|
| 88 |
-
StreamingResponse: A streaming response with the AI's reply.
|
| 89 |
-
"""
|
| 90 |
-
global chatbot
|
| 91 |
-
if chatbot is None:
|
| 92 |
-
logger.error("Chatbot not initialized.")
|
| 93 |
-
async def generate_error():
|
| 94 |
-
error_message = "Error: Chatbot not initialized. Please try again later."
|
| 95 |
-
yield error_message.encode('utf-8')
|
| 96 |
-
return StreamingResponse(generate_error(), media_type="text/plain")
|
| 97 |
-
|
| 98 |
-
async def generate():
|
| 99 |
-
try:
|
| 100 |
-
logger.info(f"Processing question: {request.question}")
|
| 101 |
-
# Use streaming to match client expectations
|
| 102 |
-
for token in chatbot.chat(request.question, stream=True):
|
| 103 |
-
# Handle hugchat response (token may be dict or string)
|
| 104 |
-
if isinstance(token, dict):
|
| 105 |
-
token_text = token.get("token", "")
|
| 106 |
-
else:
|
| 107 |
-
token_text = str(token)
|
| 108 |
-
|
| 109 |
-
if token_text:
|
| 110 |
-
logger.debug(f"Streaming token: {token_text}")
|
| 111 |
-
yield token_text.encode('utf-8')
|
| 112 |
-
else:
|
| 113 |
-
logger.warning("Empty token received.")
|
| 114 |
-
|
| 115 |
-
# Fallback response if no tokens were yielded
|
| 116 |
-
if not any(True for _ in chatbot.chat(request.question, stream=True)):
|
| 117 |
-
fallback = "Welcome, valued client! How can Abdullah Ali and our premium team bring your vision to life with a custom website ($200–$600) or AI chatbot ($119)?"
|
| 118 |
-
logger.info("Using fallback response.")
|
| 119 |
-
yield fallback.encode('utf-8')
|
| 120 |
-
except Exception as e:
|
| 121 |
-
logger.error(f"Failed to generate response: {str(e)}")
|
| 122 |
-
error_message = f"Error: Failed to generate response: {str(e)}"
|
| 123 |
-
yield error_message.encode('utf-8')
|
| 124 |
-
|
| 125 |
-
return StreamingResponse(generate(), media_type="text/plain")
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from hugchat import hugchat
|
| 2 |
from hugchat.login import Login
|
| 3 |
+
import fastapi
|
| 4 |
+
from fastapi import FastAPI, Query
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
app = FastAPI()
|
| 6 |
+
# Your HuggingFace credentials
|
| 7 |
+
EMAIL = "abdullahali1692011@gmail.com"
|
| 8 |
+
PASSWORD = "Allahisgreatest17"
|
| 9 |
+
@app.post("/ask")
|
| 10 |
+
def main(prompt: str = Query(..., description="The prompt for the AI")):
|
| 11 |
+
# Login and save cookies (optional cookie path omitted for simplicity)
|
| 12 |
+
sign = Login(EMAIL, PASSWORD)
|
| 13 |
+
cookies = sign.login(save_cookies=True)
|
| 14 |
+
|
| 15 |
+
# Initialize chatbot with cookies
|
| 16 |
+
chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
|
| 17 |
|
| 18 |
+
# Start a new conversation with your assistant ID
|
| 19 |
+
ASSISTANT_ID = "682e0c1f5f0c3d952a27498e" # Replace with your assistant ID
|
| 20 |
+
chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# Send message and get the full response (no streaming)
|
| 23 |
+
response = chatbot.chat(f"{prompt}", stream=False)
|
|
|
|
| 24 |
|
| 25 |
+
# Print full response
|
| 26 |
+
print("Assistant:", response)
|
| 27 |
+
return response
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|