Spaces:
Running
Running
File size: 16,103 Bytes
423a42f 822dfd5 dd5f028 99d7e90 6257584 99d7e90 137bcde 99d7e90 dd5f028 1af9f6b 509ca73 6d8186b 6257584 509ca73 25f7cba ec2738b 7497699 048a335 dd5f028 99d7e90 045f780 99d7e90 dd5f028 1ddb359 0e8c814 240c27b 0e8c814 5aecc17 dd5f028 99d7e90 90d319d f5522e5 99d7e90 dd5f028 99d7e90 f5522e5 dd5f028 68b816d dd5f028 99d7e90 dd5f028 99d7e90 dd5f028 99d7e90 e16e5ae 99d7e90 e16e5ae 99d7e90 dd5f028 99d7e90 dd5f028 e16e5ae dd5f028 e16e5ae dd5f028 e16e5ae dd5f028 c672f84 e16e5ae 1ddb359 c672f84 1ddb359 240c27b 1ddb359 333978a a2be7db 10f9ea6 333978a 5aecc17 0204bd8 5aecc17 0204bd8 5aecc17 0204bd8 8137971 0204bd8 8137971 0204bd8 8137971 0204bd8 8137971 0204bd8 5aecc17 10f9ea6 1af9f6b 8b77a26 dd5f028 5aecc17 dd5f028 e60d9fc 10f9ea6 e60d9fc 09a4a4b c4de2a2 e60d9fc 09a4a4b 5abdf22 09a4a4b 10f9ea6 e60d9fc ccb7aa0 370c257 24c6700 dd5f028 24c6700 dd5f028 5aecc17 dd5f028 1af9f6b 24c6700 c4de2a2 25f7cba 1af9f6b 423a42f c34d039 24c6700 25f7cba 24c6700 5abdf22 24c6700 10f9ea6 423a42f ccb7aa0 370c257 24c6700 5aecc17 c672f84 509ca73 1af9f6b |
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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
from huggingface_hub import InferenceClient
import random
from flask import Flask, request, jsonify, redirect, url_for
from flask_cors import CORS
from flask_jwt_extended import JWTManager, create_access_token
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_dance.contrib.google import make_google_blueprint, google
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.1")
app = Flask(__name__)
CORS(app)
file_path = "mentor.txt"
with open(file_path, "r") as file:
mentors_data = file.read()
file_path = "temp_mentor.txt"
with open(file_path, "r") as file:
temp_mentors_data = file.read()
@app.route('/')
def home():
return jsonify({"message": "Welcome to the Recommendation API!"})
app.config['JWT_SECRET_KEY'] = "123456"
jwt = JWTManager(app)
# Setup Google OAuth
app.config["GOOGLE_OAUTH_CLIENT_ID"] = "991031782679-f0fv60jqr9snq5u9cl7j5eimhi1b3ukp.apps.googleusercontent.com"
app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = "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"
google_bp = make_google_blueprint(scope=["profile", "email"])
app.register_blueprint(google_bp, url_prefix="/login")
# Create SQLite database
conn = sqlite3.connect('users.db', check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS user_details
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER UNIQUE,
first_name TEXT,
last_name TEXT,
school_name TEXT,
bachelors_degree TEXT,
masters_degree TEXT,
certification TEXT,
activity TEXT,
country TEXT,
data_filled BOOLEAN DEFAULT False,
FOREIGN KEY(user_id) REFERENCES users(id))''')
c.execute('''CREATE TABLE IF NOT EXISTS user_mentor
(id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, mentor_name TEXT,
FOREIGN KEY(user_id) REFERENCES users(id))''')
conn.commit()
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get('username')
password = data.get('password')
google_token = data.get('google_token')
print("Type of username:", type(username))
if google_token:
# User signing up with Google
resp = google.get("/oauth2/v2/userinfo")
if not resp.ok:
return jsonify({"message": "Failed to fetch Google user info"}), 400
google_user_info = resp.json()
google_id = google_user_info["id"]
username = google_user_info["email"]
password = None # No password for Google signup
# Check if Google user already exists in the database
existing_user = c.execute("SELECT * FROM users WHERE google_id=?", (google_id,)).fetchone()
if existing_user:
access_token = create_access_token(identity=username, expires_delta=False)
return jsonify({"access_token": access_token}), 200
# User signing up with username and password
if not username or not password:
return jsonify({"message": "Missing username or password"}), 400
print("Type of username:", type(username)) # Debug print
hashed_password = generate_password_hash(password)
try:
c.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hashed_password))
conn.commit()
access_token = create_access_token(identity=username, expires_delta=False)
return jsonify({"access_token": access_token}), 201
except sqlite3.IntegrityError:
return jsonify({"message": "Username already exists"}), 400
# Endpoint for user login and Google login
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
google_token = data.get('google_token')
if google_token:
# User logging in with Google
resp = google.get("/oauth2/v2/userinfo")
if not resp.ok:
return jsonify({"message": "Failed to fetch Google user info"}), 400
google_user_info = resp.json()
google_id = google_user_info["id"]
# Check if Google user exists in the database
user = c.execute("SELECT * FROM users WHERE google_id=?", (google_id,)).fetchone()
if user:
# Retrieve data_filled from user_details table
user_details = c.execute("SELECT data_filled FROM user_details WHERE user_id=?", (user[0],)).fetchone()
if user_details:
data_filled = user_details[0]
else:
data_filled = False # Default value if data not found
access_token = create_access_token(identity=user[1], expires_delta=False)
return jsonify({"access_token": access_token, "data_filled": data_filled}), 200
else:
return jsonify({"message": "User not found"}), 404
# User logging in with username and password
if not username or not password:
return jsonify({"message": "Missing username or password"}), 400
user = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
print(user)
if user and check_password_hash(user[2], password):
# Retrieve data_filled from user_details table
user_details = c.execute("SELECT data_filled FROM user_details WHERE user_id=?", (user[0],)).fetchone()
if user_details:
data_filled = user_details[0]
else:
data_filled = False # Default value if data not found
access_token = create_access_token(identity=username, expires_delta=False)
return jsonify({"access_token": access_token, "data_filled": data_filled}), 200
else:
return jsonify({"message": "Invalid username or password"}), 401
@app.route('/user_details', methods=['POST'])
@jwt_required()
def add_user_details():
current_user = get_jwt_identity()
data = request.get_json()
first_name = data.get('first_name')
last_name = data.get('last_name')
school_name = data.get('school_name')
bachelors_degree = data.get('bachelors_degree')
masters_degree = data.get('masters_degree')
certification = data.get('certification')
activity = data.get('activity')
country = data.get('country')
if not all([first_name, last_name, school_name, bachelors_degree, masters_degree, certification, activity, country]):
return jsonify({"message": "Missing required fields"}), 400
user = c.execute("SELECT * FROM users WHERE username=?", (current_user,)).fetchone()
if not user:
return jsonify({"message": "User not found"}), 404
user_id = user[0]
try:
c.execute("INSERT INTO user_details (user_id, first_name, last_name, school_name, bachelors_degree, "
"masters_degree, certification, activity, country, data_filled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(user_id, first_name, last_name, school_name, bachelors_degree, masters_degree, certification,
activity, country, "True"))
conn.commit()
return jsonify({"message": "User details added successfully"}), 201
except sqlite3.IntegrityError:
return jsonify({"message": "User details already exist"}), 400
@app.route('/user_details', methods=['GET'])
@jwt_required()
def get_user_details():
current_user = get_jwt_identity()
user = c.execute("SELECT * FROM users WHERE username=?", (current_user,)).fetchone()
if not user:
return jsonify({"message": "User not found"}), 404
user_id = user[0]
user_details = c.execute("SELECT * FROM user_details WHERE user_id=?", (user_id,)).fetchone()
if not user_details:
return jsonify({"message": "User details not found"}), 404
user_details_dict = {
"first_name": user_details[2],
"last_name": user_details[3],
"school_name": user_details[4],
"bachelors_degree": user_details[5],
"masters_degree": user_details[6],
"certification": user_details[7],
"activity": user_details[8],
"country": user_details[9],
"data_filled": user_details[10]
}
return jsonify(user_details_dict), 200
def format_prompt(message):
# Generate a random user prompt and bot response pair
user_prompt = "UserPrompt"
bot_response = "BotResponse"
return f"<s>[INST] {user_prompt} [/INST] {bot_response}</s> [INST] {message} [/INST]"
@app.route('/add_mentor', methods=['POST'])
def add_mentor():
data = request.get_json()
mentor_name = data.get('name')
skills = data.get('skills')
qualification = data.get('qualification')
experience = data.get('experience')
if not all([mentor_name, skills, qualification, experience]):
return jsonify({"message": "Missing mentor details"}), 400
mentor_details = f"\n{mentor_name}\nSkills: {skills}\nQualification: {qualification}\nExperience: {experience}\n"
try:
with open("temp_mentor.txt", "a") as file:
file.write(mentor_details)
return jsonify({"message": "Mentor will be added after verification"}), 201
except Exception as e:
return jsonify({"message": f"Failed to add mentor: {str(e)}"}), 500
@app.route('/verify_mentor', methods=['POST'])
def verify_mentor():
try:
with open("temp_mentor.txt", "r") as file:
mentors = file.readlines()
if not mentors:
return jsonify({"message": "No mentors to verify"}), 404
return jsonify({"mentors": mentors}), 200
except Exception as e:
return jsonify({"message": f"Failed to retrieve mentors: {str(e)}"}), 500
@app.route('/add_verified_mentors', methods=['POST'])
def add_verified_mentors():
try:
data = request.get_json()
if 'mentors' not in data:
return jsonify({"message": "Mentors data not found in request"}), 400
mentors = data['mentors']
with open("mentor.txt", "a") as mentor_file:
for mentor_details in mentors:
mentor_file.write(mentor_details + '\n')
open("temp_mentor.txt", "w").close()
return jsonify({"message": "Mentors added successfully"}), 200
except Exception as e:
return jsonify({"message": f"Failed to add mentors: {str(e)}"}), 500
@app.route('/ai_mentor', methods=['POST'])
@jwt_required()
def ai_mentor():
current_user = get_jwt_identity()
data = request.get_json()
message = data.get('message')
if not message:
return jsonify({"message": "Missing message"}), 400
temperature = 0.9
max_new_tokens = 256
top_p = 0.95
repetition_penalty = 1.0
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
# Define prompt for the conversation
prompt = f""" prompt:
Act as an mentor
User: {message}"""
formatted_prompt = format_prompt(prompt)
try:
# Generate response from the Language Model
response = client.text_generation(formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False)
return jsonify({"response": response}), 200
except Exception as e:
return jsonify({"message": f"Failed to process request: {str(e)}"}), 500
@app.route('/get_course', methods=['POST'])
@jwt_required()
def get_course():
current_user = get_jwt_identity()
temperature = 0.9
max_new_tokens = 256
top_p = 0.95
repetition_penalty = 1.0
content = request.json
user_degree = content.get('degree')
user_stream = content.get('stream')
#user_semester = content.get('semester')
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
prompt = f""" prompt:
You need to act like as recommendation engine for course recommendation for a student based on below details.
Degree: {user_degree}
Stream: {user_stream}
Based on above details recommend the courses that relate to the above details
Note: Output should be list in below format:
[course1, course2, course3,...]
Return only answer not prompt and unnecessary stuff, also dont add any special characters or punctuation marks
"""
formatted_prompt = format_prompt(prompt)
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False)
return jsonify({"ans": stream})
@app.route('/get_mentor', methods=['POST'])
@jwt_required()
def get_mentor():
current_user = get_jwt_identity()
temperature = 0.9
max_new_tokens = 256
top_p = 0.95
repetition_penalty = 1.0
content = request.json
user_degree = content.get('degree')
user_stream = content.get('stream')
#user_semester = content.get('semester')
courses = content.get('courses')
temperature = float(temperature)
if temperature < 1e-2:
temperature = 1e-2
top_p = float(top_p)
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
prompt = f""" prompt:
You need to act like as recommendataion engine for mentor recommendation for student based on below details also the list of mentors with their experience is attached.
Degree: {user_degree}
Stream: {user_stream}
courses opted:{courses}
Mentor list= {mentors_data}
Based on above details recommend the mentor that realtes to above details
Note: Output should be list in below format:
[mentor1,mentor2,mentor3,...]
Return only answer not prompt and unnecessary stuff, also dont add any special characters or punctuation marks
"""
formatted_prompt = format_prompt(prompt)
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False)
return jsonify({"ans": stream})
@app.route('/select_mentor', methods=['POST'])
@jwt_required()
def select_mentor():
current_user = get_jwt_identity()
data = request.get_json()
mentor_name = data.get('mentor_name') # Assuming this is the name of the selected mentor
if not mentor_name:
return jsonify({"message": "Missing mentor name"}), 400
# Fetch user details
user = c.execute("SELECT * FROM users WHERE username=?", (current_user,)).fetchone()
if not user:
return jsonify({"message": "User not found"}), 404
user_id = user[0]
try:
# Store selected mentor information in a new table
c.execute("INSERT INTO user_mentor (user_id, mentor_name) VALUES (?, ?)", (user_id, mentor_name))
conn.commit()
return jsonify({"message": "Mentor selected successfully"}), 201
except sqlite3.IntegrityError:
return jsonify({"message": "Failed to select mentor"}), 500
@app.route('/users', methods=['GET'])
def get_all_users():
try:
users = c.execute("SELECT * FROM users").fetchall()
users_list = [{"id": user[0], "username": user[1]} for user in users]
return jsonify({"users": users_list}), 200
except Exception as e:
return jsonify({"message": f"Failed to retrieve users: {str(e)}"}), 500
@app.route('/users', methods=['DELETE'])
def delete_all_users():
try:
c.execute("DELETE FROM users")
conn.commit()
return jsonify({"message": "All users deleted successfully"}), 200
except Exception as e:
return jsonify({"message": f"Failed to delete users: {str(e)}"}), 500
if __name__ == '__main__':
app.run(debug=True)
|