-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
225 lines (171 loc) · 6.86 KB
/
app.py
File metadata and controls
225 lines (171 loc) · 6.86 KB
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
from json import JSONEncoder
from bson import ObjectId
from flask import Flask, request, jsonify
import os
import re
from flask_cors import CORS
from pymongo import MongoClient
from dotenv import load_dotenv
from pymongo.server_api import ServerApi
from datetime import datetime
from model.room import Room
from model.user import User
from widget.objectIdencoder import ObjectIdEncoder
app = Flask(__name__)
CORS(app)
load_dotenv()
# MongoDB connection
mongo_uri = os.getenv('MONGODB_URI')
database_name = os.getenv('DATABASE_NAME')
collection_name = os.getenv('COLLECTION_NAME')
client = MongoClient(mongo_uri, server_api=ServerApi('1'))
db = client[database_name]
collection = db[collection_name]
collection2 = db['users']
rooms = db['rooms']
# Problem statement search
def extract_keywords(text):
stopwords = {'and', 'the', 'is', 'of', 'or', 'in', 'to', 'it', 'that', 'was', 'with', 'for', 'on', 'as', 'by', 'at', 'an', 'but', 'not', 'are', 'you', 'we', 'can', 'have', 'has', 'this'}
keywords = re.findall(r'\b\w+\b', text.lower())
keywords = [keyword for keyword in keywords if keyword not in stopwords]
return keywords
def calculate_percentage_match(input_keywords, statement_keywords):
if len(input_keywords) == 0:
return 0.0
match_percentage = (len(set(input_keywords) & set(statement_keywords)) / len(input_keywords)) * 100
return round(match_percentage, 2)
def search_problem_statements(input_text, min_percentage=20, page=1, results_per_page=10):
input_keywords = extract_keywords(input_text)
matching_statements = []
for doc in collection.find():
author = doc.get('Author', '')
title = doc.get('Title', '')
problem_statement = doc.get('Problem Statement', '')
contributor = doc.get('Contributor', '')
statement = f"{author} - {title} - {problem_statement} - {contributor}"
statement_keywords = extract_keywords(statement)
match_percentage = calculate_percentage_match(input_keywords, statement_keywords)
if match_percentage > min_percentage:
matching_statements.append({
'percentage': match_percentage,
'title': title,
'author': author,
'problem_statement': problem_statement,
'contributor': contributor if contributor else ''
})
matching_statements.sort(key=lambda x: x['percentage'], reverse=True)
return matching_statements
# login signup
def get_user_data(username):
user_data = collection2.find_one({identify_input_type(username): username})
return user_data
def check_user_exists(username):
return get_user_data(username) is not None
def check_user_credentials(username, password):
user_data = get_user_data(username)
if user_data:
if user_data['password'] == password:
return True
return False
def identify_input_type(input_str):
if re.match(r'^[\w\.-]+@[\w\.-]+$', input_str):
return 'email'
else:
return 'username'
# routess
@app.route('/register', methods = ['POST'])
def register():
data = request.json
name = data.get('name','')
password = data.get('password', '')
email = data.get('email', '')
username = data.get('username','')
gitlink = data.get('gitlink','')
if not name or not password or not email:
return jsonify({'status':'error', 'message': 'Username and password are required'})
if check_user_exists(username):
return jsonify({'status': 'error', 'message': 'Username already exist'})
result = collection2.insert_one({
'username': username,
'password': password,
'email':email,
'gitlink': gitlink,
'name': name
})
if result.inserted_id:
return jsonify({'status': 'success', 'message':'User created successfully'})
else:
return jsonify({'status': 'error', 'message': 'Failed to create user'})
@app.route('/login', methods = ['POST'])
def login():
data = request.json
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify({'status': 'error', 'message': 'Username and password are required'})
if check_user_credentials(username, password):
user_data = collection2.find_one({identify_input_type(username): username})
res = {'id': str(user_data['_id']),
'name': user_data['name'],
'username': user_data['username'],
'email': user_data['email'],
'gitlink': user_data['gitlink']
}
return jsonify({'status': 'success', 'info':res})
else:
return jsonify({'status':'error', 'message':'Invalid name or password'})
@app.route('/search', methods=['POST'])
def search():
try:
# Check if MongoDB is connected
client.server_info()
print("Connected")
# If connected, start the Flask app
# app.run(debug=True, ssl_context='adhoc')
except Exception as e:
print("Failed to connect to MongoDB:", e)
data = request.json
input_text = data.get('input_text', '')
min_percentage = data.get('min_percentage', 20)
page = data.get('page', 1)
results = search_problem_statements(input_text, min_percentage, page)
if results:
for i, statement in enumerate(results, start=1):
print(f"{i}. Title: {statement['title']}, Author: {statement['author']}, Problem Statement: {statement['problem_statement']}, Contributor: {statement['contributor']}")
response = {'status': 'success', 'results': results}
else:
response = {'status': 'error', 'message': 'No matching problem statements found.'}
return jsonify(response)
@app.route('/create-room', methods=['POST'])
def create_room():
data = request.json
room = Room(data)
if not room.room_name:
return jsonify({"eNTER room_name"}),400
if not room.team_members:
return jsonify({"enter room_members"}),400
if not room.problem_id:
return jsonify({"enter problem_id"}),400
mapp = {
"room_id": room.room_id,
"problem_id":str(room.problem_id),
"room_name": room.room_name,
"team_members": room.team_members,
"room_token": room.room_token,
"videocon": room.videocon,
}
collect = rooms.insert_one(mapp)
if collect.inserted_id:
mapp['_id'] = str(mapp['_id'])
return jsonify({"status":"success", "info": mapp })
else:
return jsonify({"status":"error", "message": "error occured"})
if __name__ == '__main__':
try:
# Check if MongoDB is connected
client.server_info()
print("Connected")
# If connected, start the Flask app
app.run(debug=True, ssl_context='adhoc')
except Exception as e:
print("Failed to connect to MongoDB:", e)