ParthCodes commited on
Commit
b976a31
·
verified ·
1 Parent(s): dc818ff

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +418 -116
main.py CHANGED
@@ -2,6 +2,7 @@ from flask import Flask, jsonify, request
2
  from flask_cors import CORS
3
  from pymongo.mongo_client import MongoClient
4
  from pymongo.server_api import ServerApi
 
5
  import google.generativeai as genai
6
  import urllib.parse
7
  from models import UserSchema
@@ -10,13 +11,17 @@ from flask_jwt_extended import JWTManager, create_access_token
10
  from middleware.authUser import auth_user
11
  from datetime import timedelta
12
  from controllers.demo import get_initial_data
 
 
 
13
  import os
14
 
 
 
15
  app = Flask(__name__)
16
 
17
  bcrypt = Bcrypt(app)
18
  jwt = JWTManager(app)
19
-
20
  CORS(app)
21
 
22
  app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET')
@@ -24,13 +29,15 @@ app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET')
24
  # MongoDB configuration
25
  username = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME'))
26
  password = urllib.parse.quote_plus(os.getenv('MONGO_PASSWORD'))
27
- restUri = os.getenv('REST_URI')
28
 
29
- uri = f'mongodb+srv://{username}:{password}@cluster0.iidzcbc.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0'
30
 
31
- client = MongoClient(uri)
32
  db = client.GenUpNexus
33
- users_collection = db["users3"]
 
 
34
 
35
  # Send a ping to confirm a successful connection
36
  try:
@@ -45,145 +52,412 @@ GOOGLE_API_KEY=os.getenv('GOOGLE_API_KEY')
45
  genai.configure(api_key=GOOGLE_API_KEY)
46
  model = genai.GenerativeModel('gemini-pro')
47
 
 
 
 
 
48
  @app.route('/')
49
  def index():
50
  return "Server is Running..."
51
 
52
- @app.route('/tree', methods=["POST", "GET"])
 
 
 
 
53
  def tree():
54
  if request.method == 'POST':
55
  data = request.get_json()
56
  query = data.get('query')
57
  print(query)
58
- response = model.generate_content('''I will give you a topic and you have to generate an explanation of the topic and respond with JSON structure as follows as i want to use this json are Nodes & Edges and visualise this using ReactFlow library, the json structure will be :
59
- nodes = [
60
- {
61
- id: "1",
62
- type: "input",
63
- data: {
64
- label: "Input Node",
65
- },
66
- position: { x: 250, y: 0 },
67
- },
68
- {
69
- id: "2",
70
- data: {
71
- label: "Default Node",
72
- },
73
- position: { x: 100, y: 100 },
74
- },
75
- {
76
- id: "3",
77
- type: "output",
78
- data: {
79
- label: "Output Node",
80
- },
81
- position: { x: 400, y: 100 },
82
- },
83
- {
84
- id: "4",
85
- type: "custom",
86
- position: { x: 100, y: 200 },
87
- data: {
88
- selects: {
89
- "handle-0": "smoothstep",
90
- "handle-1": "smoothstep",
91
- },
92
- },
93
- },
94
- {
95
- id: "5",
96
- type: "output",
97
- data: {
98
- label: "custom style",
99
- },
100
- className: "circle",
101
- style: {
102
- background: "#2B6CB0",
103
- color: "white",
104
- },
105
- position: { x: 400, y: 200 },
106
- sourcePosition: Position.Right,
107
- targetPosition: Position.Left,
108
- },
109
- {
110
- id: "6",
111
- type: "output",
112
- style: {
113
- background: "#63B3ED",
114
- color: "white",
115
- width: 100,
116
- },
117
- data: {
118
- label: "Node",
119
- },
120
- position: { x: 400, y: 325 },
121
- sourcePosition: Position.Right,
122
- targetPosition: Position.Left,
123
- },
124
- {
125
- id: "7",
126
- type: "default",
127
- className: "annotation",
128
- data: {
129
- label: (
130
- <>
131
- On the bottom left you see the <strong>Controls</strong> and the
132
- bottom right the <strong>MiniMap</strong>. This is also just a node 🥳
133
- </>
134
- ),
135
  },
136
- draggable: false,
137
- selectable: false,
138
- position: { x: 150, y: 400 },
139
- },
140
- ];
141
-
142
- edges = [
143
- { id: "e1-2", source: "1", target: "2", label: "this is an edge label" },
144
- { id: "e1-3", source: "1", target: "3", animated: true },
145
  {
146
- id: "e4-5",
147
- source: "4",
148
- target: "5",
149
- type: "smoothstep",
150
- sourceHandle: "handle-0",
151
- data: {
152
- selectIndex: 0,
 
 
 
 
 
 
 
 
 
153
  },
154
- markerEnd: {
155
- type: MarkerType.ArrowClosed,
 
 
156
  },
 
 
 
 
 
 
157
  },
158
  {
159
- id: "e4-6",
160
- source: "4",
161
- target: "6",
162
- type: "smoothstep",
163
- sourceHandle: "handle-1",
164
- data: {
165
- selectIndex: 1,
166
  },
167
- markerEnd: {
168
- type: MarkerType.ArrowClosed,
 
 
169
  },
170
- },
171
- ];
 
 
 
 
 
 
 
172
  Topic is: ''' + query)
173
 
174
  # print(response.text)
175
  return jsonify({'success': True, 'data': response.text})
176
  # return temp
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  @app.route('/interview', methods=["POST", "GET"])
179
  def interview():
180
  if request.method == 'POST':
181
  data = request.get_json()
 
182
  if data.get('from') == 'client':
183
- return "Success"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  elif data.get('from') == 'gradio':
185
  print(data)
186
- return "Success"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
 
189
  # User Routes
@@ -236,7 +510,7 @@ def signin():
236
  expires = timedelta(days=7)
237
  access_token = create_access_token(identity={"email": user['email'], "id": str(user['_id'])}, expires_delta=expires)
238
 
239
- res = {"name": user['name'], "email": user['email']}
240
 
241
  return jsonify({"result": res, "token": access_token}), 200
242
 
@@ -256,10 +530,38 @@ def delete_account():
256
  print(e)
257
  return jsonify({"message": "Something went wrong"}), 500
258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  @app.route('/mindmap/demo', methods=['POST'])
260
  def mindmapDemo():
261
  data = request.json
262
- print(data)
263
  return get_initial_data(), 200
264
 
265
 
 
2
  from flask_cors import CORS
3
  from pymongo.mongo_client import MongoClient
4
  from pymongo.server_api import ServerApi
5
+ from bson.objectid import ObjectId
6
  import google.generativeai as genai
7
  import urllib.parse
8
  from models import UserSchema
 
11
  from middleware.authUser import auth_user
12
  from datetime import timedelta
13
  from controllers.demo import get_initial_data
14
+ from controllers.mindmap import saveMindmap, getMindmap, deleteMindmap, getMindmapByid
15
+ import json
16
+ from dotenv import load_dotenv
17
  import os
18
 
19
+ load_dotenv()
20
+
21
  app = Flask(__name__)
22
 
23
  bcrypt = Bcrypt(app)
24
  jwt = JWTManager(app)
 
25
  CORS(app)
26
 
27
  app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET')
 
29
  # MongoDB configuration
30
  username = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME'))
31
  password = urllib.parse.quote_plus(os.getenv('MONGO_PASSWORD'))
32
+ restUri = os.getenv('REST_URI');
33
 
34
+ uri = f'mongodb+srv://{username}:{password}{restUri}'
35
 
36
+ client = MongoClient(uri, server_api=ServerApi('1'))
37
  db = client.GenUpNexus
38
+ users_collection = db["users"]
39
+ interviews_collection = db["interviews"]
40
+ savedMindmap = db["savedMindmap"]
41
 
42
  # Send a ping to confirm a successful connection
43
  try:
 
52
  genai.configure(api_key=GOOGLE_API_KEY)
53
  model = genai.GenerativeModel('gemini-pro')
54
 
55
+ # Caches to reduce no of queries to MongoDB...
56
+ user_id_ping = {'current': 0}
57
+ user_chats = {}
58
+
59
  @app.route('/')
60
  def index():
61
  return "Server is Running..."
62
 
63
+ @app.route('/index')
64
+ def index2():
65
+ return "routes checking..."
66
+
67
+ @app.route('/trees', methods=["POST", "GET"])
68
  def tree():
69
  if request.method == 'POST':
70
  data = request.get_json()
71
  query = data.get('query')
72
  print(query)
73
+ response = model.generate_content('''I will give you a topic and you have to generate an explanation of the topic in points in hierarchical tree structure and respond with JSON structure as follows:
74
+ {
75
+ "name": "Java",
76
+ "children": [
77
+ {
78
+ "name": "Development Environment",
79
+ "children": [
80
+ {
81
+ "name": "Java Source Code",
82
+ "value": ".java files",
83
+ "description": "Human-readable code written with Java syntax."
84
+ },
85
+ {
86
+ "name": "Java Development Kit (JDK)",
87
+ "children": [
88
+ {
89
+ "name": "Compiler",
90
+ "value": "translates to bytecode",
91
+ "description": "Transforms Java source code into bytecode instructions understood by the JVM."
92
+ },
93
+ {
94
+ "name": "Java Class Library (JCL)",
95
+ "value": "predefined classes and functions",
96
+ "description": "Provides a collection of reusable code for common functionalities."
97
+ }
98
+ ]
99
+ }
100
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  },
 
 
 
 
 
 
 
 
 
102
  {
103
+ "name": "Execution",
104
+ "children": [
105
+ {
106
+ "name": "Java Runtime Environment (JRE)",
107
+ "children": [
108
+ {
109
+ "name": "Java Virtual Machine (JVM)",
110
+ "value": "executes bytecode",
111
+ "description": "Software program that interprets and executes bytecode instructions."
112
+ },
113
+ {
114
+ "name": "Class Loader",
115
+ "value": "loads bytecode into memory",
116
+ "description": "Loads .class files containing bytecode into JVM memory for execution."
117
+ }
118
+ ]
119
  },
120
+ {
121
+ "name": "Bytecode",
122
+ "value": ".class files (platform-independent)",
123
+ "description": "Machine-independent instructions generated by the compiler, executable on any system with JVM."
124
  },
125
+ {
126
+ "name": "Just-In-Time (JIT) Compilation (optional)",
127
+ "value": "improves performance by translating bytecode to machine code",
128
+ "description": "Technique that translates frequently used bytecode sections into native machine code for faster execution."
129
+ }
130
+ ]
131
  },
132
  {
133
+ "name": "Key Features",
134
+ "children": [
135
+ {
136
+ "name": "Object-Oriented Programming",
137
+ "value": "uses objects and classes",
138
+ "description": "Programs are structured around objects that encapsulate data and behavior."
 
139
  },
140
+ {
141
+ "name": "Platform Independent (write once, run anywhere)",
142
+ "value": "bytecode runs on any system with JVM",
143
+ "description": "Java code can be compiled once and run on any platform with a JVM installed."
144
  },
145
+ {
146
+ "name": "Garbage Collection",
147
+ "value": "automatic memory management",
148
+ "description": "JVM automatically reclaims memory from unused objects, simplifying memory management for developers."
149
+ }
150
+ ]
151
+ }
152
+ ]
153
+ }
154
  Topic is: ''' + query)
155
 
156
  # print(response.text)
157
  return jsonify({'success': True, 'data': response.text})
158
  # return temp
159
 
160
+
161
+
162
+
163
+ @app.route('/tree/demo', methods=["POST"])
164
+ def treeDemo():
165
+ if request.method == 'POST':
166
+ data = request.get_json()
167
+ query = data.get('query')
168
+ print(query)
169
+ response = model.generate_content('''Generate a comprehensive knowledge map representing the user's query, suitable for ReactFlow visualization.
170
+
171
+ **Prompt:** {query}
172
+
173
+ **Structure:**
174
+
175
+ - Top-level node: Represent the user's query.
176
+ - Sub-nodes branching out based on the query's relevance:
177
+ - Leverage external knowledge sources (e.g., Wikipedia, knowledge graphs, domain-specific APIs) to identify relevant sub-concepts, related entities, and potential relationships.
178
+ - Consider including different categories of sub-nodes:
179
+ - **Concepts:** Core ideas or principles related to the query.
180
+ - **Subfields:** Specialized areas within the main topic.
181
+ - **Applications:** Practical uses of the concept or subfield.
182
+ - **Tools and Technologies:** Software or platforms used to implement the concepts.
183
+ - **Examples:** Illustrative instances or use cases.
184
+ - **Historical Context:** Milestones or key figures in the topic's development.
185
+ - **See Also:** Links to broader concepts or related areas for the further exploration.
186
+
187
+
188
+ **Content:**
189
+
190
+ - Each node should have a label describing the concept, entity, or tool.
191
+ - Optionally, include brief descriptions, definitions, or key points within the nodes or as tooltips.
192
+ - Consider using icons to visually represent different categories of nodes (e.g., light bulb for concepts, gear for tools, calendar for historical context, puzzle piece for subfields).
193
+ - there should be atmax 10 nodes in the knowledge map.
194
+ - Also follow the n-ary tree structure for better visualization.
195
+ - Ensure the knowledge map is visually appealing, well-organized, and easy to navigate.
196
+
197
+ **Desired Format:**
198
+
199
+ - JSON structure compatible with ReactFlow:
200
+ - nodes (list): id, position, data (label, description, icon(if required), category), type(input, output or custom), style (background, color).
201
+ - edges (list): id, source, target, label(if required), animated (true or false), style (stroke).
202
+ - keep the position of nodes spaced out for better visualization.
203
+ - always keep the top-level node at the center of the visualization.
204
+ - keep atleast 2 edges "animated":true.
205
+ - Strictly keep the first node with style having color property with value blue and background property with value #0FFFF0.
206
+ - Strictly keep the second node with type property value as custom.
207
+ - You can style the nodes with different colors and edges with different colors.
208
+ - to edit edges add style with stroke property and a hexcode value to it.
209
+
210
+ Topic is: ''' + query)
211
+
212
+ # response.text(8,)
213
+ print(response.text)
214
+ json_data = response.text
215
+ modified_json_data = json_data[8:-3]
216
+ return jsonify({'success': True, 'data': modified_json_data})
217
+ # return temp
218
+
219
+
220
+ def res(user_id):
221
+ avg_text = 0
222
+ avg_code = 0
223
+ count = 0
224
+ for i, ele in enumerate(user_chats[user_id]['chat'].history):
225
+ if i == 0:
226
+ continue
227
+
228
+ if ele.role == 'model':
229
+ temp = json.loads(ele.parts[0].text)
230
+ print(temp)
231
+ if 'question' in temp.keys():
232
+ continue
233
+ elif 'next_question' in temp.keys() or 'end' in temp.keys():
234
+ count += 1
235
+ avg_text += temp['text_correctness']
236
+ if temp['code_correctness']:
237
+ avg_code += temp['code_correctness']
238
+ print(json.loads(ele.parts[0].text), end='\n\n')
239
+
240
+ avg_text /= count
241
+ avg_code /= count
242
+
243
+ user_chats[user_id]['test_results'] = {'avg_text': avg_text, 'avg_code': avg_code}
244
+
245
+ return True
246
+
247
+
248
  @app.route('/interview', methods=["POST", "GET"])
249
  def interview():
250
  if request.method == 'POST':
251
  data = request.get_json()
252
+ print(data)
253
  if data.get('from') == 'client':
254
+ user_id = data.get('user_id')
255
+ request_type = data.get('type')
256
+
257
+ if request_type == 1: # Initialize Questionarrie.
258
+ chat = model.start_chat(history=[])
259
+ user_chats[user_id] = {}
260
+ user_chats[user_id]['chat'] = chat
261
+ user_chats[user_id]['processed'] = False
262
+
263
+ position = data.get('position')
264
+ round = data.get('round')
265
+ difficulty_level = data.get('difficulty_level')
266
+ company_name = data.get('company_name')
267
+
268
+ user_chats[user_id]['position'] = position
269
+ user_chats[user_id]['round'] = round
270
+ user_chats[user_id]['difficulty_level'] = difficulty_level
271
+ user_chats[user_id]['company_name'] = company_name
272
+
273
+ response = chat.send_message('''You are a Interviewer. I am providing you with the the position for which the inerview is, Round type, difficulty level of the interview to be conducted, Company name.
274
+ You need to generate atmost 2 interview questions one after another.
275
+ The questions may consists of writing a small code along with text as well.
276
+
277
+ Now generate first question in following JSON format:
278
+ {
279
+ "question": "What is ...?"
280
+ }
281
+
282
+ I will respond to the question in the following JSON format:
283
+ {
284
+ "text_answer": "answer ...",
285
+ "code": "if any...."
286
+ }
287
+
288
+ Now after evaluating the answers you need to respond in the following JSON format:
289
+ {
290
+ "next_question": "What is ...?",
291
+ "text_correctness": "Test the correctness of text and return a range from 1 to 5 of correctness of text.",
292
+ "text_suggestions": "Some suggestions regarding the text_answer.... in string format."
293
+ "code_correctness": "Test the correctness of code and return a range from 1 to 5 of correctness of code",
294
+ "code_suggestions": "Any suggestions or optimizations to the code...in string format.",
295
+ }
296
+
297
+ At the end of the interview if no Questions are required then respond in the following format:
298
+ {
299
+ "text_correctness": "Test the correctness of text and return a range from 1 to 5 of correctness of text.",
300
+ "text_suggestions": "Some suggestions regarding the text_answer...."
301
+ "code_correctness": "Test the correctness of code and return a range from 1 to 5 of correctness of code",
302
+ "code_suggestions": "Any suggestions or optimizations to the code...",
303
+ "end": "No more Questions thanks for your time."
304
+ }
305
+
306
+ Here are the details:
307
+ Position : '''+ position + '''
308
+ Round: '''+ round + '''
309
+ Difficullty Level : '''+ difficulty_level + '''
310
+ Company Interview : ''' + company_name)
311
+ print(response.text)
312
+ temp = json.loads(response.text)
313
+ user_chats[user_id]['qa'] = [{'question': temp['question']}]
314
+ return jsonify({'success': True, 'data': response.text})
315
+
316
+ if request_type == 2:
317
+ text_data = data.get('text_data')
318
+ code = data.get('code')
319
+
320
+ chat = user_chats[user_id]['chat']
321
+ response = chat.send_message('''{"text_answer": "''' + text_data + '''", "code": "''' + code + '''"}''')
322
+
323
+ print(response.text)
324
+
325
+ json_text = json.loads(response.text)
326
+
327
+ for i, ele in enumerate(user_chats[user_id]['qa']):
328
+ if i == len(user_chats[user_id]['qa'])-1:
329
+ ele['text_answer'] = text_data
330
+ ele['code_answer'] = code
331
+ ele['text_correctness'] = json_text['text_correctness']
332
+ ele['text_suggestions'] = json_text['text_suggestions']
333
+ ele['code_correctness'] = json_text['code_correctness']
334
+ ele['code_suggestions'] = json_text['code_suggestions']
335
+
336
+ try:
337
+ if json_text['end']:
338
+ user_id_ping['current'] = user_id
339
+ if res(user_id):
340
+ print(user_chats[user_id])
341
+ return jsonify({'success': True, 'data': response.text, 'end': True})
342
+ except Exception as e:
343
+ print(e)
344
+
345
+ user_chats[user_id]['qa'].append({'question': json_text['next_question']})
346
+
347
+ return jsonify({'success': True, 'data': response.text, 'end': False})
348
+
349
+
350
  elif data.get('from') == 'gradio':
351
  print(data)
352
+ user_id = data.get('user_id')
353
+ user_chats[user_id]['processed'] = True
354
+ user_chats[user_id]['gradio_results'] = {'total_video_emotions': data.get('total_video_emotions'), 'emotions_final': data.get('emotions_final'), 'body_language': data.get('body_language'), 'distraction_rate': data.get('distraction_rate'), 'formatted_response': data.get('formatted_response'), 'total_transcript_sentiment': data.get('total_transcript_sentiment')}
355
+
356
+ emotion_weights = {
357
+ 'admiration': 0.8,
358
+ 'amusement': 0.7,
359
+ 'angry': -0.8,
360
+ 'annoyance': -0.7,
361
+ 'approval': 0.9,
362
+ 'calm': 0.8,
363
+ 'caring': 0.8,
364
+ 'confusion': -0.5,
365
+ 'curiosity': 0.6,
366
+ 'desire': 0.7,
367
+ 'disappointment': -0.8,
368
+ 'disapproval': -0.9,
369
+ 'disgust': -0.9,
370
+ 'embarrassment': -0.7,
371
+ 'excitement': 0.8,
372
+ 'fear': -0.8,
373
+ 'fearful': -0.8,
374
+ 'gratitude': 0.9,
375
+ 'grief': -0.9,
376
+ 'happy': 0.9,
377
+ 'love': 0.9,
378
+ 'nervousness': -0.6,
379
+ 'optimism': 0.8,
380
+ 'pride': 0.9,
381
+ 'realization': 0.7,
382
+ 'relief': 0.8,
383
+ 'remorse': -0.8,
384
+ 'sad': -0.9,
385
+ 'surprise': 0.7,
386
+ 'surprised': 0.7,
387
+ 'neutral': 0.0
388
+ }
389
+
390
+ temp = data.get('total_video_emotions')
391
+ temp2 = data.get('emotions_final')
392
+ temp3 = data.get('formatted_response')
393
+ temp4 = data.get('total_transcript_sentiment')
394
+
395
+ total_video_emotion_score = sum(temp[emotion] * emotion_weights[emotion] for emotion in temp)
396
+ total_video_emotion_normalized_score = ((total_video_emotion_score + 1) / 2) * 9 + 1
397
+
398
+ emotion_final_score = sum(temp2[emotion] * emotion_weights[emotion] for emotion in temp2)
399
+ emotion_final_normalized_score = ((emotion_final_score + 1) / 2) * 9 + 1
400
+
401
+ speech_sentiment_score = sum(temp3[emotion] * emotion_weights[emotion] for emotion in temp3)
402
+ speech_sentiment_normalized_score = ((speech_sentiment_score + 1) / 2) * 9 + 1
403
+
404
+ total_transcript_sentiment_score = sum(temp4[emotion] * emotion_weights[emotion] for emotion in temp4)
405
+ total_transcript_sentiment_normalized_score = ((total_transcript_sentiment_score + 1) / 2) * 9 + 1
406
+
407
+ body_language_score = data.get('body_language')['Good'] * 10
408
+ distraction_rate_score = data.get('distraction_rate') * 10
409
+
410
+ avg_text_score = user_chats[user_id]['test_results']['avg_text']
411
+ avg_code_score = user_chats[user_id]['test_results']['avg_code']
412
+
413
+ interview_score = (total_video_emotion_normalized_score + emotion_final_normalized_score + speech_sentiment_normalized_score + total_transcript_sentiment_normalized_score + body_language_score + distraction_rate_score + avg_text_score + avg_code_score)/7
414
+
415
+ print(interview_score)
416
+ user_chats[user_id]['interview_score'] = interview_score
417
+
418
+ user_chats[user_id]['user_id'] = user_id
419
+ print(user_chats[user_id])
420
+
421
+ # Store user_chats[user_id] into MongoDB...
422
+ del user_chats[user_id]["chat"]
423
+ result = interviews_collection.insert_one(user_chats[user_id])
424
+ print(result)
425
+
426
+ return jsonify({'success': True})
427
+
428
+
429
+ @app.route('/result', methods=['POST', 'GET'])
430
+ def result():
431
+ if request.method == 'POST':
432
+ data = request.get_json()
433
+ user_id = data.get('user_id')
434
+
435
+ if data.get('type') == 1:
436
+ result = interviews_collection.find({ "user_id" : user_id}, {"_id" : 1, "company_name" : 1, "difficulty_level" : 1, "interview_score" : 1, "position" : 1, "round" : 1 })
437
+ temp = []
438
+ for ele in result:
439
+ ele['_id'] = str(ele['_id'])
440
+ temp.append(ele)
441
+
442
+ return jsonify({'success': True, 'data': temp})
443
+
444
+ elif data.get('type') == 2:
445
+ result2 = interviews_collection.find_one({ "_id": ObjectId(data.get("_id")), "user_id": user_id })
446
+ if result2:
447
+ result2['_id'] = str(result2['_id'])
448
+ print(result2)
449
+ return jsonify({'success': True, 'data': result2})
450
+ else:
451
+ if not user_chats[user_id]['processed']:
452
+ return jsonify({'processing': True})
453
+ else:
454
+ return jsonify({'error': "No such record found."})
455
+
456
+
457
+ @app.route('/useridping', methods=['GET'])
458
+ def useridping():
459
+ if request.method == 'GET':
460
+ return jsonify(user_id_ping)
461
 
462
 
463
  # User Routes
 
510
  expires = timedelta(days=7)
511
  access_token = create_access_token(identity={"email": user['email'], "id": str(user['_id'])}, expires_delta=expires)
512
 
513
+ res = {"name": user['name'], "email": user['email'], "user_id": str(user['_id'])}
514
 
515
  return jsonify({"result": res, "token": access_token}), 200
516
 
 
530
  print(e)
531
  return jsonify({"message": "Something went wrong"}), 500
532
 
533
+ # mindmap routes
534
+ @app.route('/mindmap/save', methods=['POST'])
535
+ @auth_user
536
+ def mindmapSave():
537
+ userId = request.userId
538
+ data = request.json
539
+ return saveMindmap(data, userId, savedMindmap)
540
+
541
+ @app.route('/mindmap/get', methods=['GET'])
542
+ @auth_user
543
+ def mindmapGet():
544
+ userId = request.userId
545
+ return getMindmap(userId, savedMindmap)
546
+
547
+ @app.route('/mindmap/get/<id>', methods=['GET'])
548
+ @auth_user
549
+ def mindmapGetById(id):
550
+ userId = request.userId
551
+ return getMindmapByid(userId, id, savedMindmap)
552
+
553
+ @app.route('/mindmap/delete', methods=['POST'])
554
+ @auth_user
555
+ def mindmapDelete():
556
+ userId = request.userId
557
+ data = request.json
558
+ return deleteMindmap(userId, data, savedMindmap)
559
+
560
+
561
  @app.route('/mindmap/demo', methods=['POST'])
562
  def mindmapDemo():
563
  data = request.json
564
+ print(data);
565
  return get_initial_data(), 200
566
 
567