triflix commited on
Commit
2bba15a
·
verified ·
1 Parent(s): 192da81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -26
app.py CHANGED
@@ -1,40 +1,91 @@
1
- from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
 
 
 
 
 
2
  from fastapi.staticfiles import StaticFiles
3
  from fastapi.templating import Jinja2Templates
4
- from typing import List
5
 
 
6
  app = FastAPI()
 
 
7
  app.mount("/static", StaticFiles(directory="static"), name="static")
8
 
 
9
  templates = Jinja2Templates(directory="templates")
10
 
11
- class ConnectionManager:
12
- def __init__(self):
13
- self.active_connections: List[WebSocket] = []
 
14
 
15
- async def connect(self, websocket: WebSocket):
16
- await websocket.accept()
17
- self.active_connections.append(websocket)
18
 
19
- def disconnect(self, websocket: WebSocket):
20
- self.active_connections.remove(websocket)
 
 
 
 
 
 
 
 
21
 
22
- async def broadcast(self, message: str):
23
- for connection in self.active_connections:
24
- await connection.send_text(message)
 
25
 
26
- manager = ConnectionManager()
 
 
 
 
 
 
 
 
 
 
 
 
27
 
 
28
  @app.get("/")
29
- async def get(request: Request):
30
- return templates.TemplateResponse('index.html', {'request': request})
31
-
32
- @app.websocket('/ws')
33
- async def websocket_endpoint(websocket: WebSocket):
34
- await manager.connect(websocket)
35
- try:
36
- while True:
37
- data = await websocket.receive_text()
38
- await manager.broadcast(data)
39
- except WebSocketDisconnect:
40
- manager.disconnect(websocket)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from datetime import datetime
4
+
5
+ from fastapi import FastAPI, Request, Form
6
+ from fastapi.responses import RedirectResponse
7
  from fastapi.staticfiles import StaticFiles
8
  from fastapi.templating import Jinja2Templates
 
9
 
10
+ # --- App Initialization ---
11
  app = FastAPI()
12
+
13
+ # Mount static files (for CSS)
14
  app.mount("/static", StaticFiles(directory="static"), name="static")
15
 
16
+ # Setup Jinja2 templates
17
  templates = Jinja2Templates(directory="templates")
18
 
19
+ # --- Data Storage ---
20
+ # Define the path for our temporary data storage
21
+ TMP_DIR = Path("tmp")
22
+ CHAT_FILE = TMP_DIR / "chat_history.json"
23
 
24
+ # Ensure the tmp directory exists
25
+ TMP_DIR.mkdir(exist_ok=True)
 
26
 
27
+ # --- Helper Functions ---
28
+ def load_chat_history():
29
+ """Loads chat history from the JSON file."""
30
+ if CHAT_FILE.exists():
31
+ with open(CHAT_FILE, "r") as f:
32
+ try:
33
+ return json.load(f)
34
+ except json.JSONDecodeError:
35
+ return []
36
+ return []
37
 
38
+ def save_chat_history(data):
39
+ """Saves chat history to the JSON file."""
40
+ with open(CHAT_FILE, "w") as f:
41
+ json.dump(data, f, indent=4)
42
 
43
+ def get_bot_response(user_message: str) -> str:
44
+ """A simple rule-based bot response generator."""
45
+ lower_message = user_message.lower()
46
+ if "hello" in lower_message or "hi" in lower_message:
47
+ return "Hello there! How can I help you today?"
48
+ elif "how are you" in lower_message:
49
+ return "I'm just a bunch of code, but I'm doing great! Thanks for asking."
50
+ elif "help" in lower_message:
51
+ return "I am a simple global chatbot. Just type a message and I'll try to respond. Everyone sees the same conversation."
52
+ elif "time" in lower_message:
53
+ return f"The current server time is {datetime.now().strftime('%H:%M:%S')}."
54
+ else:
55
+ return f"You said: '{user_message}'"
56
 
57
+ # --- API Endpoints ---
58
  @app.get("/")
59
+ def read_root(request: Request):
60
+ """
61
+ Renders the main chat page.
62
+ It loads the chat history and passes it to the template.
63
+ """
64
+ chat_history = load_chat_history()
65
+ return templates.TemplateResponse(
66
+ "index.html", {"request": request, "chat_history": chat_history}
67
+ )
68
+
69
+ @app.post("/chat")
70
+ def post_chat_message(message: str = Form(...)):
71
+ """
72
+ Handles new chat messages.
73
+ It saves the user's message and the bot's response to the history.
74
+ """
75
+ # Load current history
76
+ chat_history = load_chat_history()
77
+
78
+ # Add user message
79
+ user_entry = {"sender": "You", "message": message, "timestamp": datetime.now().isoformat()}
80
+ chat_history.append(user_entry)
81
+
82
+ # Get and add bot response
83
+ bot_message = get_bot_response(message)
84
+ bot_entry = {"sender": "Bot", "message": bot_message, "timestamp": datetime.now().isoformat()}
85
+ chat_history.append(bot_entry)
86
+
87
+ # Save updated history
88
+ save_chat_history(chat_history)
89
+
90
+ # Redirect back to the main page to see the updated chat
91
+ return RedirectResponse(url="/", status_code=303)