abdullahalioo commited on
Commit
85582c9
·
verified ·
1 Parent(s): 2f3bde3

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +44 -76
main.py CHANGED
@@ -1,8 +1,5 @@
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
  import logging
7
 
8
  # Set up logging
@@ -12,78 +9,49 @@ logger = logging.getLogger(__name__)
12
  # Initialize FastAPI app
13
  app = FastAPI()
14
 
15
- # HuggingFace credentials from environment variables
16
- EMAIL = "abdullahali1692011@gmail.com"
17
- PASSWORD = "Allahisgreatest17"
18
- ASSISTANT_ID = "682e0c1f5f0c3d952a27498e"
19
-
20
- # Global chatbot instance
21
- chatbot = None
22
-
23
- # Pydantic model for request body
24
- class PromptRequest(BaseModel):
25
- prompt: str
26
-
27
- # Lifespan handler for startup and shutdown
28
- from contextlib import asynccontextmanager
29
-
30
- @asynccontextmanager
31
- async def lifespan(app: FastAPI):
32
- global chatbot
33
- try:
34
- # Validate credentials
35
- if not EMAIL or not PASSWORD or not ASSISTANT_ID:
36
- logger.error("Missing environment variables: EMAIL=%s, PASSWORD=%s, ASSISTANT_ID=%s",
37
- EMAIL, "****" if PASSWORD else None, ASSISTANT_ID)
38
- raise ValueError("HuggingFace credentials or assistant ID not provided in environment variables")
39
-
40
- # Log in to HuggingFace
41
- sign = Login(EMAIL, PASSWORD)
42
- try:
43
- # Try login without cookie_path_dir to avoid file system issues
44
- cookies = sign.login(save_cookies=False)
45
- logger.info("Successfully logged in to HuggingFace without saving cookies")
46
- except Exception as e:
47
- logger.error("Login failed: %s", str(e))
48
- raise
49
-
50
- # Initialize chatbot
51
- chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
52
- chatbot.new_conversation(assistant=ASSISTANT_ID, switch_to=True)
53
- logger.info("Chatbot initialized with assistant ID: %s", ASSISTANT_ID)
54
-
55
- except Exception as e:
56
- logger.error("Failed to initialize chatbot: %s", str(e))
57
- raise HTTPException(status_code=500, detail=f"Failed to initialize chatbot: {str(e)}")
58
-
59
- yield # Application runs here
60
-
61
- # Shutdown: Clean up (optional)
62
- logger.info("Shutting down application")
63
-
64
- # Attach lifespan handler to FastAPI app
65
- app.lifespan = lifespan
66
-
67
- # Endpoint to handle chat requests
68
- @app.post("/ask")
69
- async def ask(prompt_request: PromptRequest):
70
- try:
71
- if not chatbot:
72
- logger.error("Chatbot not initialized")
73
- raise HTTPException(status_code=500, detail="Chatbot not initialized")
74
-
75
- # Send prompt to chatbot
76
- response = chatbot.chat(prompt_request.prompt, stream=False)
77
- logger.info("Received response for prompt: %s", prompt_request.prompt)
78
-
79
- # Return structured response
80
- return {"status": "success", "response": response}
81
- except Exception as e:
82
- logger.error("Error processing request: %s", str(e))
83
- raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
84
 
85
  # Health check endpoint
86
  @app.get("/health")
87
  async def health():
88
- return {"status": "healthy", "chatbot_initialized": chatbot is not None}
89
-
 
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import HTMLResponse
 
 
 
3
  import logging
4
 
5
  # Set up logging
 
9
  # Initialize FastAPI app
10
  app = FastAPI()
11
 
12
+ # Serve HTML page
13
+ @app.get("/", response_class=HTMLResponse)
14
+ async def serve_html():
15
+ logger.info("Serving HTML page")
16
+ return """
17
+ <html>
18
+ <head>
19
+ <title>AI Chemistry Chat</title>
20
+ <style>
21
+ body { font-family: Arial, sans-serif; margin: 20px; }
22
+ #response { white-space: pre-wrap; border: 1px solid #ccc; padding: 10px; min-height: 100px; }
23
+ input { width: 300px; padding: 5px; }
24
+ button { padding: 5px 10px; }
25
+ </style>
26
+ </head>
27
+ <body>
28
+ <h1>AI Chemistry Chat</h1>
29
+ <input type="text" id="prompt" placeholder="Ask about chemistry..." value="Tell me something I might not know about chemistry." />
30
+ <button onclick="sendPrompt()">Send</button>
31
+ <div id="response"></div>
32
+ <script src="https://js.puter.com/v2/"></script>
33
+ <script>
34
+ async function sendPrompt() {
35
+ const prompt = document.getElementById('prompt').value;
36
+ const responseDiv = document.getElementById('response');
37
+ responseDiv.innerHTML = 'Loading...';
38
+ try {
39
+ const resp = await puter.ai.chat(prompt, { model: 'grok-beta', stream: true });
40
+ responseDiv.innerHTML = '';
41
+ for await (const part of resp) {
42
+ responseDiv.innerHTML += part?.text?.replaceAll('\\n', '<br>') || '';
43
+ }
44
+ } catch (error) {
45
+ responseDiv.innerHTML = 'Error: ' + error.message;
46
+ }
47
+ }
48
+ </script>
49
+ </body>
50
+ </html>
51
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  # Health check endpoint
54
  @app.get("/health")
55
  async def health():
56
+ logger.info("Health check requested")
57
+ return {"status": "healthy"}