rohangbs commited on
Commit
1774186
·
1 Parent(s): 42de216

Deploy chatbot

Browse files
Files changed (3) hide show
  1. Dockerfile +23 -0
  2. app.py +128 -0
  3. requirements.txt +12 -0
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use the official Python image.
2
+ FROM python:3.9
3
+
4
+ # Set environment variables
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ # Set the working directory in the container
8
+ WORKDIR /app
9
+
10
+ # Copy the requirements file
11
+ COPY requirements.txt requirements.txt
12
+
13
+ # Install dependencies
14
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
15
+
16
+ # Copy the content of the local src directory to the working directory
17
+ COPY . /app
18
+
19
+ # Expose port 7860
20
+ EXPOSE 7860
21
+
22
+ # Command to run the app
23
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+ from fastapi import FastAPI, Request, Depends, HTTPException
4
+ from fastapi.responses import JSONResponse, RedirectResponse
5
+ from pydantic import BaseModel
6
+ from functools import wraps
7
+ import hashlib
8
+ from textblob import TextBlob
9
+ from groq import Groq
10
+ from starlette.middleware.sessions import SessionMiddleware
11
+ from starlette.responses import RedirectResponse
12
+ from starlette.staticfiles import StaticFiles
13
+
14
+ app = FastAPI()
15
+
16
+ # Secret key for sessions
17
+ app.add_middleware(SessionMiddleware, secret_key=os.urandom(24))
18
+
19
+ # Initialize the Groq client with your API key
20
+ client = Groq(api_key='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')
21
+
22
+ # Database initialization
23
+ def init_db():
24
+ conn = sqlite3.connect('chat_history.db')
25
+ c = conn.cursor()
26
+
27
+ # Users table
28
+ c.execute('''CREATE TABLE IF NOT EXISTS users
29
+ (id INTEGER PRIMARY KEY AUTOINCREMENT,
30
+ username TEXT UNIQUE NOT NULL,
31
+ password TEXT NOT NULL,
32
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP)''')
33
+
34
+ c.execute('''CREATE TABLE IF NOT EXISTS chats
35
+ (id INTEGER PRIMARY KEY AUTOINCREMENT,
36
+ user_id INTEGER NOT NULL,
37
+ user_message TEXT NOT NULL,
38
+ bot_response TEXT NOT NULL,
39
+ sentiment_score REAL,
40
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
41
+ FOREIGN KEY (user_id) REFERENCES users (id))''')
42
+
43
+ conn.commit()
44
+ conn.close()
45
+
46
+ init_db()
47
+
48
+ # Helper functions
49
+ def hash_password(password):
50
+ return hashlib.sha256(password.encode()).hexdigest()
51
+
52
+ def get_sentiment(text):
53
+ analysis = TextBlob(text)
54
+ return analysis.sentiment.polarity
55
+
56
+ def store_chat(user_id, user_message, bot_response, sentiment_score):
57
+ conn = sqlite3.connect('chat_history.db')
58
+ c = conn.cursor()
59
+ c.execute('''INSERT INTO chats (user_id, user_message, bot_response, sentiment_score)
60
+ VALUES (?, ?, ?, ?)''', (user_id, user_message, bot_response, sentiment_score))
61
+ conn.commit()
62
+ conn.close()
63
+
64
+ # New generate_response function using Groq API
65
+ def generate_response(prompt):
66
+ try:
67
+ chat_completion = client.chat.completions.create(
68
+ messages=[
69
+ {
70
+ "role": "system",
71
+ "content": "You are Amara, a chatbot created to help. Be helpful, truthful, and attentive to emotions. Consider the previous conversation context for personalized responses. Keep it short and concise."
72
+ },
73
+ {
74
+ "role": "user",
75
+ "content": prompt,
76
+ }
77
+ ],
78
+ model="llama3-70b-8192",
79
+ temperature=0.5,
80
+ max_tokens=1024,
81
+ top_p=1,
82
+ stop=None,
83
+ stream=False
84
+ )
85
+ return chat_completion.choices[0].message.content
86
+ except Exception as e:
87
+ return f"Error generating response: {e}"
88
+
89
+ # Define request models
90
+ class UserMessage(BaseModel):
91
+ message: str
92
+
93
+ @app.post("/chat")
94
+ async def chat_endpoint(request: Request, message: UserMessage):
95
+ user_message = message.message
96
+ user_id = request.session.get("user_id")
97
+
98
+ if not user_id:
99
+ raise HTTPException(status_code=401, detail="User not logged in")
100
+
101
+ # Get user's recent chat history for context
102
+ conn = sqlite3.connect('chat_history.db')
103
+ c = conn.cursor()
104
+ c.execute('''SELECT user_message, bot_response
105
+ FROM chats
106
+ WHERE user_id = ?
107
+ ORDER BY timestamp DESC LIMIT 5''', (user_id,))
108
+ recent_chats = c.fetchall()
109
+ conn.close()
110
+
111
+ context = "Previous conversation:\n"
112
+ for user_msg, bot_msg in reversed(recent_chats):
113
+ context += f"User: {user_msg}\nAmara: {bot_msg}\n"
114
+
115
+ full_prompt = f"{context}\nUser: {user_message}\nAmara:"
116
+
117
+ try:
118
+ bot_response = generate_response(full_prompt)
119
+ sentiment_score = get_sentiment(user_message)
120
+ store_chat(user_id, user_message, bot_response, sentiment_score)
121
+
122
+ return JSONResponse({
123
+ 'response': bot_response,
124
+ 'sentiment': sentiment_score
125
+ })
126
+ except Exception as e:
127
+ raise HTTPException(status_code=500, detail=f"I apologize, but I encountered an error: {str(e)}")
128
+
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask==3.0.3
2
+ huggingface_hub==0.24.3
3
+ textblob==0.18.0.post0
4
+ torch==2.1.2
5
+ transformers==4.45.2
6
+ fastapi
7
+ uvicorn[standard]
8
+ sqlite3
9
+ textblob
10
+ groq
11
+ hashlib
12
+ pydantic