-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
274 lines (210 loc) · 9.45 KB
/
app.py
File metadata and controls
274 lines (210 loc) · 9.45 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
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
from flask import Flask, request, jsonify
import firebase_admin
from firebase_admin import credentials, db
import os
from openai import OpenAI
from collections import deque
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("OPEN_AI_KEY")
client = OpenAI(api_key=api_key)
app = Flask(__name__)
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://guyapp-958a6-default-rtdb.firebaseio.com/'
})
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
required_fields = ['phone_number', 'name', 'skills', 'connections', 'location', 'photo', 'password']
missing = [field for field in required_fields if field not in data]
if missing:
return jsonify({'error': f'Missing fields: {", ".join(missing)}'}), 400
phone_number = data['phone_number']
invalid_chars = ['.', '$', '#', '[', ']', '/']
if not isinstance(phone_number, str) or any(char in phone_number for char in invalid_chars):
return jsonify({'error': 'Invalid phone number'}), 400
if not isinstance(data['skills'], list) or not all(isinstance(s, str) for s in data['skills']):
return jsonify({'error': 'Skills must be a list of strings'}), 400
if not isinstance(data['connections'], list):
return jsonify({'error': 'Connections must be a list'}), 400
ref = db.reference('/users')
ref.child(phone_number).set({
'name': data['name'],
'skills': data['skills'],
'connections': data['connections'],
'location': data['location'],
'photo': data['photo'],
'password': data['password']
})
allskills_ref = db.reference('/allskills')
current_skills = allskills_ref.get() or {}
for skill in data['skills']:
current_skills[skill] = True
allskills_ref.set(current_skills)
return jsonify({'id': phone_number, 'message': 'User created successfully'}), 201
@app.route('/users/<phone_number>/connections', methods=['GET'])
def get_user_connections(phone_number):
invalid_chars = ['.', '$', '#', '[', ']', '/']
if any(char in phone_number for char in invalid_chars):
return jsonify({'error': 'Invalid phone number'}), 400
users_ref = db.reference('/users')
user_data = users_ref.child(phone_number).get()
if not user_data:
return jsonify({'error': f'User {phone_number} not found'}), 404
connection_ids = user_data.get('connections', [])
connection_profiles = []
for conn_id in connection_ids:
conn_data = users_ref.child(conn_id).get()
if conn_data:
connection_profiles.append({
'phone_number': conn_id,
'name': conn_data.get('name'),
'skills': conn_data.get('skills', []),
'location': conn_data.get('location'),
'photo': conn_data.get('photo')
})
return jsonify({'connections': connection_profiles}), 200
@app.route('/auth', methods=['POST'])
def authenticate_user():
data = request.get_json()
phone_number = data.get('phone_number')
password = data.get('password')
if not phone_number or not password:
return jsonify({'error': 'Both phone_number and password are required'}), 400
users_ref = db.reference('/users')
user_data = users_ref.child(phone_number).get()
if not user_data:
return jsonify({'auth': False, 'message': 'User not found'}), 404
stored_password = user_data.get('password')
if stored_password is None:
return jsonify({'auth': False, 'message': 'No password found for this user'}), 400
if password == stored_password:
return jsonify({'auth': True}), 200
else:
return jsonify({'auth': False}), 200
@app.route('/users/<phone_number>', methods=['GET'])
def get_user(phone_number):
if not isinstance(phone_number, str):
return jsonify({'error': 'Phone number must be a string'}), 400
invalid_chars = ['.', '$', '#', '[', ']', '/']
if any(char in phone_number for char in invalid_chars):
return jsonify({'error': 'Phone number contains invalid characters for a Firebase key'}), 400
ref = db.reference('/users')
user_data = ref.child(phone_number).get()
if user_data:
return jsonify({'phone_number': phone_number, 'user_data': user_data}), 200
else:
return jsonify({'error': 'User not found'}), 404
@app.route('/users/<phone_number>/add', methods=['POST'])
def add_connections(phone_number):
if not isinstance(phone_number, str):
return jsonify({'error': 'Phone number must be a string'}), 400
invalid_chars = ['.', '$', '#', '[', ']', '/']
if any(char in phone_number for char in invalid_chars):
return jsonify({'error': 'Phone number contains invalid characters'}), 400
data = request.get_json()
new_connections = data.get('connections')
if not isinstance(new_connections, list) or not all(isinstance(c, str) for c in new_connections):
return jsonify({'error': 'connections must be a list of phone numbers (strings)'}), 400
users_ref = db.reference('/users')
user_ref = users_ref.child(phone_number)
user_data = user_ref.get()
if not user_data:
return jsonify({'error': f'User {phone_number} not found'}), 404
existing_connections = set(user_data.get('connections', []))
valid_new_connections = []
for conn in new_connections:
if conn not in existing_connections:
if users_ref.child(conn).get():
valid_new_connections.append(conn)
updated_connections = list(existing_connections.union(valid_new_connections))
user_ref.update({'connections': updated_connections})
return jsonify({
'added_connections': valid_new_connections,
'total_connections': updated_connections
}), 200
@app.route('/users/<phone_number>/remove/<connection_id>', methods=['POST'])
def remove_connections(phone_number, connection_id):
invalid_chars = ['.', '$', '#', '[', ']', '/']
if any(char in phone_number for char in invalid_chars) or any(char in connection_id for char in invalid_chars):
return jsonify({'error': 'Invalid characters in phone numbers'}), 400
users_ref = db.reference('/users')
user_ref = users_ref.child(phone_number)
user_data = user_ref.get()
if not user_data:
return jsonify({'error': f'User {phone_number} not found'}), 404
current_connections = user_data.get('connections', [])
if connection_id not in current_connections:
return jsonify({'message': f'{connection_id} was not in connections list'}), 200
updated_connections = [c for c in current_connections if c != connection_id]
user_ref.update({'connections': updated_connections})
return jsonify({
'message': f'Connection {connection_id} removed from user {phone_number}',
'total_connections': updated_connections
}), 200
@app.route('/match_prompt', methods=['POST'])
def match_prompt():
data = request.get_json()
prompt = data.get('prompt')
start_phone = data.get('phone_number')
if not prompt or not start_phone:
return jsonify({'error': 'Both prompt and phone_number are required'}), 400
allskills_ref = db.reference('/allskills')
allskills = list((allskills_ref.get() or {}).keys())
try:
response = client.chat.completions.create(model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a skill-matching assistant. Given a user prompt and a list of skills, identify which skills are most likely to help answer or satisfy the prompt"
},
{
"role": "user",
"content": [
{"type": "text", "text": f"Prompt: {prompt}\nSkills: {', '.join(allskills)}\n\nReturn a list of matching skills found as a comma separated list"}
]
}
],
max_tokens=100)
matched_skills_text = response.choices[0].message.content.strip()
matched_skills = [skill.strip() for skill in matched_skills_text.split(',') if skill.strip() in allskills]
print(matched_skills_text)
print(matched_skills)
except Exception as e:
return jsonify([]), 500
if not matched_skills:
return jsonify([]), 200
visited = set()
queue = deque([[start_phone, []]])
results = []
users_ref = db.reference('/users')
while queue:
current_node = queue.popleft()
current_phone = current_node[0]
curr_path = current_node[1]
if current_phone in visited:
continue
visited.add(current_phone)
user_data = users_ref.child(current_phone).get()
if not user_data:
continue
user_skills = set(user_data.get('skills', []))
if any(skill in user_skills for skill in matched_skills):
results.append({
'matched_skills': matched_skills,
'path': curr_path[1:],
'matched_user': {
'phone_number': current_phone,
'name': user_data.get('name'),
'skills': list(user_skills),
'location': user_data.get('location')
}
})
connections = user_data.get('connections', [])
for conn in connections:
if isinstance(conn, str) and conn not in visited:
queue.append([conn, curr_path + [user_data.get('name')]])
return jsonify(results), 200
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=8000)