-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
176 lines (149 loc) · 6.35 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
from flask import Flask, render_template, request, redirect, url_for, session, jsonify
import psycopg2
from psycopg2.extras import RealDictCursor
from groq import Groq
from sentence_transformers import SentenceTransformer
import os
model = SentenceTransformer('all-MiniLM-L6-v2')
# api="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"
# Initialize the Groq client with your API key
# client = Groq(api_key="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")
# client = Groq("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")
client = Groq(os.getenv("GROQ_API_KEY"))
# queary=""" From the text given above, write a vey brief and precise anaswer of this question(if it can be answered from the text) in a formal language but do not mension that you are giving the answer from any text and also give the link if any(otherwise dont mention about the link) in the text only in clickable fromat at the last of answer to know more, if the question is irrelevent, show appropriate message, the question is: """
queary=""" From this text, answer shortly the question given next (if the text contains the answer) without mentioning the text,
if text has link, give the link in the end of answer only in clickable format otherwise don't mension about the link that it is present or not,
if the question is irrelevant, show appropriate message,
the question is: """
# Function to generate embedding for user question
def generate_embedding(question):
return model.encode(question).tolist()
# Database connection parameters
DB_PARAMS = {
"dbname": "suchatbot",
"user": "avnadmin",
"password": os.getenv("password"),
"host": os.getenv("host"),
"port": 13189
}
# Connect to the database
conn = psycopg2.connect(**DB_PARAMS)
cursor = conn.cursor(cursor_factory=RealDictCursor)
def get_top_similar_questions(user_question, top_n=5):
# Generate embedding for the user question
user_embedding = generate_embedding(user_question)
# Query to calculate similarity and retrieve top N questions
query = f"""
SELECT
sr_no,
topic_id,
question,
1 - (embedding <=> %s::VECTOR) AS similarity -- Cast to VECTOR
FROM
questions
ORDER BY
similarity DESC
LIMIT %s;
"""
cursor.execute(query, (user_embedding, top_n))
top_questions = cursor.fetchall()
# Retrieve paragraphs for the corresponding topic_ids
topic_ids = tuple(q['topic_id'] for q in top_questions)
paragraphs_query = """
SELECT topic_id, paragraph
FROM topics
WHERE topic_id IN %s;
"""
cursor.execute(paragraphs_query, (topic_ids,))
paragraphs = cursor.fetchall()
# Map topic_id to paragraphs for display
paragraphs_dict = {p['topic_id']: p['paragraph'] for p in paragraphs}
# Combine the questions and paragraphs
result = []
for question in top_questions:
result.append({
"sr_no": question["sr_no"],
"question": question["question"],
"similarity": question["similarity"],
"paragraph": paragraphs_dict.get(question["topic_id"], "No paragraph found")
})
# cursor.close()
# conn.close()
return result
app = Flask(__name__)
app.secret_key = 'su-sitare-chatbot'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json.get('message')
# Process the message here and generate a response
top_results=get_top_similar_questions(user_message)
sourcetext=""
for i in range(len(top_results)):
if top_results[i]['paragraph'] not in sourcetext:
sourcetext+=(" "+top_results[i]['paragraph'])
completion = client.chat.completions.create(
model="llama-3.3-70b-versatile", # model
messages=[
{"role": "system", "content": "You are a University chatbot assistent specialized in English language"},
{"role": "user", "content": sourcetext+queary+user_message}
],
temperature=1, # Controls creativity (higher = more creative)
max_tokens=1024, # Limit on response length
top_p=1, # Sampling parameter for diverse outputs
stream=True, # Enables streaming
stop=None # No stop sequence
)
# Process and print the streamed response
response_message=""
for chunk in completion:
response_message+=chunk.choices[0].delta.content or ""
return jsonify({'response': response_message})
@app.route('/feedback', methods=['POST'])
def record_feedback():
data = request.json
question_text = data.get('question_text')
feedback = data.get('feedback') # 1 for like, 0 for dislike
if not question_text or feedback not in [0, 1]:
return jsonify({'error': 'Invalid data'}), 400
try:
# Insert feedback into the database
cursor.execute(
"""
INSERT INTO feedback (question_text, feedback)
VALUES (%s, %s)
""",
(question_text, feedback)
)
conn.commit()
return jsonify({'success': True})
except Exception as e:
conn.rollback()
return jsonify({'error': str(e)}), 500
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username == "admin" and password=="aks@sitare123":
session['username'] = username
return redirect(url_for('admin'))
else:
error = 'Invalid username or password'
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
@app.route('/admin')
def admin():
cursor.execute(" select * from feedback")
data=cursor.fetchall()
return render_template('admin.html', data=data)
if __name__ == '__main__':
# app.run(debug=True)
port = int(os.environ.get("PORT", 5000)) # Default to 5000 if PORT is not set
app.run(host="0.0.0.0", port=port)