-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepopack-output.txt
6715 lines (6002 loc) · 209 KB
/
repopack-output.txt
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
================================================================
Repopack Output File
================================================================
This file was generated by Repopack on: 2024-08-23T15:13:47.195Z
Purpose:
--------
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
File Format:
------------
The content is organized as follows:
1. This header section
2. Repository structure
3. Multiple file entries, each consisting of:
a. A separator line (================)
b. The file path (File: path/to/file)
c. Another separator line
d. The full contents of the file
e. A blank line
Usage Guidelines:
-----------------
1. This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
2. When processing this file, use the separators and "File:" markers to
distinguish between different files in the repository.
3. Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
Notes:
------
- Some files may have been excluded based on .gitignore rules and Repopack's
configuration.
- Binary files are not included in this packed representation. Please refer to
the Repository Structure section for a complete list of file paths, including
binary files.
For more information about Repopack, visit: https://github.com/yamadashy/repopack
================================================================
Repository Structure
================================================================
.do/
app.yaml
.github/
workflows/
gitleaks.yml
tests.yml
.pytest_cache/
v/
cache/
lastfailed
nodeids
stepwise
.gitignore
CACHEDIR.TAG
README.md
webapp/
public/
_redirects
.htaccess
404.html
favicon.ico
index.html
og-image.jpg
src/
assets/
logo.png
components/
ui/
AnimatedNumber.vue
SortableList.vue
TextAnimate.vue
TypeWriter.vue
BarChart.vue
CreateView.vue
FancyButton.vue
FancyInput.vue
HomeView.vue
NavItem.vue
NotFound.vue
ResultsView.vue
ScaleChart.vue
ShareView.vue
SiteHeader.vue
SurveyChips.vue
SurveyExpiryChip.vue
TakeSurvey.vue
ToastView.vue
locales/
en.ts
services/
api.ts
App.vue
i18n.ts
index.css
main.ts
router.ts
shims-vue.d.ts
static.json
.env.example
.gitignore
babel.config.js
Dockerfile
frontend-nginx.conf
jsconfig.json
package.json
postcss.config.js
README.md
tailwind.config.js
todo.md
tsconfig.json
vue.config.js
.coverage
.env.example
.gitignore
api_endpoints.md
app.py
docker-compose.yml
Dockerfile
id_manager.py
LICENSE
nginx.conf
Procfile
requirements.txt
sample_surveys.py
setup_mongo.py
snowflake.py
test_survey_results.py
================================================================
Repository Files
================================================================
================
File: .env.example
================
MONGO_URI=mongodb://localhost:27017/percept
================
File: .gitignore
================
__pycache__/
*.pyc
.venv/
.DS_Store
.env
#webapp folder
# Dependencies
webapp/node_modules
webapp/.pnp
.pnp.js
# Testing
webapp/coverage
# Production
webapp/build
webapp/dist
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Vue.js specific
.DS_Store
webapp/node_modules
webapp/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
================
File: Dockerfile
================
FROM python:3.9-slim
WORKDIR /app
# Copy requirements and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Install wget for the wait-for script
RUN apt-get update && apt-get install -y wget
# Download wait-for script
RUN wget -O /usr/local/bin/wait-for https://raw.githubusercontent.com/eficode/wait-for/master/wait-for
RUN chmod +x /usr/local/bin/wait-for
# Pre-download NLTK data files
# -d option may have other consequences. testing for now
RUN python -m nltk.downloader -d /workspace/nltk_data words vader_lexicon wordnet
# Copy the rest of the application code
COPY . .
# Expose port 5001
EXPOSE 5001
CMD ["gunicorn", "-b", "0.0.0.0:5001","--timeout", "240", "app:app"]
================
File: LICENSE
================
MIT License
Copyright (c) 2024 Narayan Babu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================
File: Procfile
================
web: gunicorn --bind 0.0.0.0:$PORT app:app
================
File: api_endpoints.md
================
# Percept API Endpoints
## Base URL: `/api/v1`
### 1. Create Survey
- **Endpoint**: `POST /surveys`
- **Description**: Create a new survey
- **Request Body**:
```json
{
"title": "string",
"description": "string (optional)",
"questions": [
{
"text": "string",
"response_type": "string",
"response_scale_max": "integer (optional, default is 5)",
"creator_answer": "integer or boolean"
}
]
}
```
- **Response**:
```json
{
"survey_id": "long",
"share_link": "string",
"user_code": "long",
"questions": [
{
"id": "integer",
"text": "string"
}
]
}
```
### 2. Get Survey
- **Endpoint**: `GET /surveys/{survey_id}`
- **Description**: Retrieve survey details
- **Response**:
```json
{
"title": "string",
"description": "string",
"questions": [
{
"id": "integer",
"text": "string",
"response_type": "string",
"response_scale_max": "integer (only for 'scale' type)"
}
]
}
```
### 3. Submit Survey Answers
- **Endpoint**: `POST /surveys/{survey_id}/answers`
- **Description**: Submit answers for a survey
- **Request Body**:
```json
{
"answers": [
{
"question_id": "integer",
"answer": "integer or boolean"
}
]
}
```
- **Response**:
```json
{
"user_code": "long",
"deviation_from_creator": "float",
"deviation_from_others": "float",
"overall_deviation": "float"
}
```
### 4. Get Survey Results by Survey ID
- **Endpoint**: `GET /surveys/{survey_id}/results`
- **Description**: Retrieve survey results for a specific survey
- **Query Parameters**:
- `user_code`: "long" (required)
- **Response**:
```json
{
"survey_id": "long",
"title": "string",
"description": "string",
"created_at": "long",
"user_type": "string",
"questions": [
{
"id": "integer",
"text": "string",
"type": "string",
"scale_max": "integer (for scale questions)",
"average_score": "float (for scale questions)",
"standard_deviation": "float (for scale questions)",
"user_score": "integer or boolean (if applicable)",
"user_deviation": "float (for scale questions, if applicable)",
"true_percentage": "float (for boolean questions)",
"false_percentage": "float (for boolean questions)"
}
],
"overall_statistics": {
"average_deviation_from_aggregate": "float",
"deviation_from_creator": "float (for participants)",
"deviation_from_others": "float (for participants)",
"overall_deviation": "float"
}
}
```
### 5. Get Survey Results by User Code
- **Endpoint**: `GET /surveys/results`
- **Description**: Retrieve survey results for a user across all surveys
- **Query Parameters**:
- `user_code`: "long" (required)
- **Response**: Same as "Get Survey Results by Survey ID"
## Notes
- Question IDs are simple integers starting from 1 for each survey.
- The `response_type` can be "scale" or "boolean".
- For "scale" type questions, `response_scale_max` specifies the maximum value of the scale. If not provided, it defaults to 5.
- The server returns appropriate HTTP status codes (200 for success, 201 for creation, 400 for bad request, 404 for not found, etc.)
- Error responses include a message explaining the error.
- The `user_type` in the results can be either "creator" or "participant".
- For the creator, some statistics like `deviation_from_creator` are not applicable and may be omitted from the response.
================
File: app.py
================
# app.py
import datetime
from statistics import StatisticsError, mean, stdev
import time
from flask import Flask, request, jsonify
from flask_pymongo import PyMongo
from flask_cors import CORS
import os
import logging
from id_manager import IDManager
from pymongo.errors import ConnectionFailure
from snowflake import Snowflake53
app = Flask(__name__)
# Add the CORS configuration here
allowed_origins = [
"http://localhost",
"http://localhost:8080",
os.environ.get("APP_URL", "https://i.nyn.me")
]
CORS(app, resources={
r"/v1/*": {"origins": allowed_origins},
r"/api/v1/*": {"origins": allowed_origins}
})
#CORS(app, resources={r"/api/*": {"origins": "*"}}, supports_credentials=True)
api_prefix = os.getenv('API_PREFIX', '') # Default to empty string if not set
# Initialize the generator with a random number
snowflake = Snowflake53(1,1)
# Constants
MINIMUM_RESPONSES = 5
ID_SUGGESTIONS = 5
INITIAL_ID_RESERVE = 300 # Number of IDs to generate initially
DEFAULT_EXPIRY = datetime.timedelta(days=5) # New constant for default expiry
# Set up logging
logging.basicConfig(level=logging.DEBUG)
# MongoDB configuration
if app.testing:
app.config["MONGO_URI"] = "mongodb://localhost:27017/backfeed_test"
else:
app.config["MONGO_URI"] = os.environ.get("MONGO_URI", "mongodb://localhost:27017/percept")
mongo = PyMongo(app)
# Initialize IDManager
id_manager = IDManager(mongo.db)
def make_tz_aware(dt):
if isinstance(dt, str):
dt = datetime.datetime.fromisoformat(dt)
if dt.tzinfo is None:
return dt.replace(tzinfo=datetime.UTC)
return dt
def initialize_db(max_retries=5, delay=5):
for attempt in range(max_retries):
try:
# The ismaster command is cheap and does not require auth.
mongo.db.command('ismaster')
logging.info("Successfully connected to MongoDB")
return True
except ConnectionFailure:
if attempt < max_retries - 1:
logging.error(f"Failed to connect to MongoDB. Retrying in {delay} seconds...")
time.sleep(delay)
else:
logging.error("Failed to connect to MongoDB after maximum retries")
return False
def generate_unique_id():
return snowflake.generate()
# Initialize the ID reserve
with app.app_context():
if initialize_db():
try:
id_manager.initialize_reserve(INITIAL_ID_RESERVE)
app.logger.info(f"Initialized ID reserve with {INITIAL_ID_RESERVE} IDs")
except Exception as e:
app.logger.error(f"Failed to initialize ID reserve: {str(e)}")
else:
app.logger.error("Failed to initialize database connection")
@app.before_first_request
def startup_logger():
app.logger.info("Application started. Testing MongoDB connection...")
try:
# Perform a simple operation to test the connection
mongo.db.command('ping')
app.logger.info("MongoDB connection successful")
except Exception as e:
app.logger.error(f"MongoDB connection failed: {str(e)}")
@app.route(f'{api_prefix}/')
def home():
return "Welcome to the Percept API", 200
def get_participant_bucket(count):
if count < 10:
return "< 10"
elif 10 <= count < 100:
return "10-100"
elif 100 <= count < 1000:
return "100-1000"
else:
return "1000+"
@app.route(f'{api_prefix}/v1/ids/check', methods=['GET'])
def check_id():
id_to_check = request.args.get('id')
if not id_to_check:
return jsonify({'error': 'No ID provided'}), 400
if not id_manager.is_valid_id_format(id_to_check):
return jsonify({
'id': id_to_check,
'available': False,
'error': 'Invalid ID format. ID must be at least 5 characters long and contain only letters, numbers, and hyphens.'
}), 400
available = id_manager.is_id_available(id_to_check)
return jsonify({
'id': id_to_check,
'available': available
})
@app.route(f'{api_prefix}/v1/ids', methods=['GET'])
def get_ids():
preferred = request.args.get('id')
count = int(request.args.get('count', ID_SUGGESTIONS))
ids = id_manager.get_ids(count, preferred)
return jsonify({
'ids': ids
})
@app.route(f'{api_prefix}/v1/surveys', methods=['POST'])
def create_survey():
app.logger.debug("Received POST request to /api/v1/surveys")
data = request.json
app.logger.debug(f"Request data: {data}")
if 'survey_id' not in data :
data['survey_id'] = id_manager.get_ids()[0]
app.logger.debug("Creating surveyID: "+data['survey_id'])
if 'user_code' not in data :
data['user_code'] = id_manager.get_ids()[0]
app.logger.debug("Creating userCode: "+data['user_code'])
if not data or 'title' not in data or 'questions' not in data or 'user_code' not in data:
app.logger.warning("Invalid request data")
return jsonify({'error': 'Invalid request data'}), 400
try:
survey_id = data['survey_id']
user_code = data['user_code']
# Check if the IDs are available, including reserved IDs
if not id_manager.is_id_available(survey_id, include_reserved=True):
app.logger.warning(f"Requested survey ID is not available: survey_id={survey_id}")
return jsonify({'error': 'Requested survey ID is not available'}), 400
if not id_manager.is_id_available(user_code, include_reserved=True):
app.logger.warning(f"Requested user code is not available: user_code={user_code}")
return jsonify({'error': 'Requested user code is not available'}), 400
# Handle expiry date
expiry_date = data.get('expiry')
if expiry_date:
expiry_date = make_tz_aware(datetime.datetime.fromisoformat(expiry_date))
else:
expiry_date = make_tz_aware(datetime.datetime.now(datetime.UTC) + DEFAULT_EXPIRY)
survey = {
'survey_id': survey_id,
'title': data['title'],
'description': data.get('description', ''),
'questions': [
{
'id': i + 1,
'text': q['text'],
'response_type': q['response_type'],
'response_scale_max': q.get('response_scale_max', MINIMUM_RESPONSES),
'creator_answer': q['creator_answer']
} for i, q in enumerate(data['questions'])
],
'user_code': user_code,
'expiry_date': expiry_date
}
# Insert the survey into the database
result = mongo.db.surveys.insert_one(survey)
if result.inserted_id:
app.logger.debug(f"Survey created with ID: {survey_id}")
# Mark the IDs as used only after successful insertion
id_manager.mark_id_as_used(survey_id)
id_manager.mark_id_as_used(user_code)
response = jsonify({
'survey_id': survey_id,
'share_link': f"/participate/{survey_id}",
'user_code': user_code,
'questions': [{'id': q['id'], 'text': q['text']} for q in survey['questions']],
'expiry_date': expiry_date.isoformat()
})
app.logger.debug(f"Sending response: {response.get_data(as_text=True)}")
return response, 201
else:
app.logger.error("Failed to insert survey into database")
return jsonify({'error': 'Failed to create survey'}), 500
except Exception as e:
app.logger.error(f"Error creating survey: {str(e)}")
return jsonify({'error': 'Internal server error'}), 500
@app.route(f'{api_prefix}/v1/surveys/<string:survey_id>', methods=['GET'])
def get_survey(survey_id):
app.logger.debug(f"Received GET request for survey ID: {survey_id}")
survey = mongo.db.surveys.find_one({'survey_id': survey_id})
if not survey:
app.logger.warning(f"Survey not found: {survey_id}")
return jsonify({'error': 'Survey not found'}), 404
# Check if the survey has expired
expiry_date = make_tz_aware(survey.get('expiry_date', datetime.datetime.now(datetime.UTC) + DEFAULT_EXPIRY))
is_expired = expiry_date < datetime.datetime.now(datetime.UTC)
if is_expired:
return jsonify({'error': 'Survey has expired', 'expired': True}), 410
# Remove the _id field from the survey dict
survey.pop('_id', None)
# Calculate trending status
twenty_four_hours_ago = datetime.datetime.now(datetime.UTC) - datetime.timedelta(hours=24)
recent_answers = mongo.db.answers.find_one({
'survey_id': survey_id,
'submitted_at': {'$gte': twenty_four_hours_ago}
})
is_trending = bool(recent_answers)
# Calculate participant bucket
total_answers = mongo.db.answers.count_documents({'survey_id': survey_id})
participant_bucket = get_participant_bucket(total_answers)
app.logger.debug(f"Found survey: {survey}")
return jsonify({
'survey_id': survey['survey_id'],
'title': survey['title'],
'description': survey.get('description', ''),
'questions': [
{
'id': q['id'],
'text': q['text'],
'response_type': q['response_type'],
'response_scale_max': q.get('response_scale_max')
} for q in survey['questions']
],
'is_trending': is_trending,
'participant_bucket': participant_bucket,
'expiry_date': expiry_date.isoformat(),
'expired': is_expired
})
@app.route(f'{api_prefix}/v1/surveys/<string:survey_id>/answers', methods=['POST'])
def submit_answers(survey_id):
app.logger.debug(f"Received POST request to submit answers for survey ID: {survey_id}")
data = request.json
app.logger.debug(f"Request data: {data}")
if not data or 'answers' not in data:
app.logger.warning("Invalid request data: 'answers' not found in request")
return jsonify({'error': 'Invalid request data: answers not provided'}), 400
try:
# Fetch the survey
survey = mongo.db.surveys.find_one({'survey_id': survey_id})
if not survey:
app.logger.warning(f"Survey not found: {survey_id}")
return jsonify({'error': 'Survey not found'}), 404
# Validate answers
valid_questions = {str(q['id']): q for q in survey['questions']} # Convert to string
for answer in data['answers']:
if 'question_id' not in answer or 'answer' not in answer:
app.logger.warning(f"Invalid answer format: {answer}")
return jsonify({'error': f"Invalid answer format: {answer}"}), 400
question_id = str(answer['question_id']) # Convert to string
if question_id not in valid_questions:
app.logger.warning(f"Invalid question ID: {question_id}")
return jsonify({'error': f"Invalid question ID: {question_id}"}), 400
question = valid_questions[question_id]
if question['response_type'] == 'scale':
if not isinstance(answer['answer'], (int, float)) or not (1 <= answer['answer'] <= question['response_scale_max']):
app.logger.warning(f"Invalid answer for scale question {question_id}: {answer['answer']}")
return jsonify({'error': f"Invalid answer for question {question_id}: must be between 1 and {question['response_scale_max']}"}), 400
elif question['response_type'] == 'boolean':
if not isinstance(answer['answer'], bool):
app.logger.warning(f"Invalid answer for boolean question {question_id}: {answer['answer']}")
return jsonify({'error': f"Invalid answer for question {question_id}: must be a boolean"}), 400
# Use provided user_code, if not, generate a new one
user_code = data.get('user_code', id_manager.get_id())
answer_submission = {
'survey_id': survey_id,
'user_code': user_code,
'answers': {str(answer['question_id']): answer['answer'] for answer in data['answers']},
'submitted_at': datetime.datetime.now(datetime.UTC)
}
result = mongo.db.answers.insert_one(answer_submission)
# Mark the user_code as used
id_manager.mark_id_as_used(user_code)
# Calculate deviations (placeholder logic - you'll need to implement the actual calculation)
deviation_from_creator = 0.5 # placeholder
deviation_from_others = 0.3 # placeholder
overall_deviation = 0.4 # placeholder
response = jsonify({
'user_code': user_code,
'deviation_from_creator': deviation_from_creator,
'deviation_from_others': deviation_from_others,
'overall_deviation': overall_deviation
})
app.logger.debug(f"Sending response: {response.get_data(as_text=True)}")
return response, 201
except Exception as e:
app.logger.error(f"Error submitting answers: {str(e)}")
return jsonify({'error': 'Internal server error'}), 500
@app.route(f'{api_prefix}/v1/surveys/<string:survey_id>/results', methods=['GET'])
def get_survey_results(survey_id):
user_code = request.args.get('user_code')
return process_results(survey_id, user_code)
@app.route(f'{api_prefix}/v1/surveys/results', methods=['GET'])
def get_results_by_user_code():
user_code = request.args.get('user_code')
if not user_code:
return jsonify({'error': 'User code is required'}), 400
# Try to find the survey based on the user_code (for creators)
survey = mongo.db.surveys.find_one({'user_code': user_code})
if survey:
return process_results(survey['survey_id'], user_code)
# If not found in surveys, look in answers (for participants)
answer = mongo.db.answers.find_one({'user_code': user_code})
if answer:
return process_results(answer['survey_id'], user_code)
return jsonify({'error': 'No survey found for this user code'}), 404
def process_results(survey_id, user_code):
logging.info(f"Getting results for survey {survey_id}, user_code {user_code}")
if not user_code:
logging.warning("User code is missing")
return jsonify({'error': 'User code is required'}), 400
survey = mongo.db.surveys.find_one({'survey_id': survey_id})
if not survey:
logging.warning(f"Survey {survey_id} not found")
return jsonify({'error': 'Survey not found'}), 404
# Check if user is creator
is_creator = (user_code == survey['user_code'])
logging.info(f"User is creator: {is_creator}")
# Get all answers for this survey
answers = list(mongo.db.answers.find({'survey_id': survey_id}))
logging.info(f"Found {len(answers)} answers for survey {survey_id}")
# Check if the user_code exists in the answers
user_answer = next((a for a in answers if a['user_code'] == user_code), None)
if not user_answer and not is_creator:
logging.warning(f"Invalid user code: {user_code}")
return jsonify({'error': 'Invalid user code'}), 404
logging.info(f"Creator ID is: {survey['user_code']}")
current_responses = len(answers)
now_time = datetime.datetime.now(datetime.UTC)
# Calculate trending status
twenty_four_hours_ago = now_time - datetime.timedelta(hours=24)
recent_answers = mongo.db.answers.find_one({
'survey_id': survey_id,
'submitted_at': {'$gte': twenty_four_hours_ago}
})
# Calculate participant bucket
total_answers = len(answers)
is_trending = bool(recent_answers)
participant_bucket = get_participant_bucket(total_answers)
# Check expiry
expiry_date = make_tz_aware(survey.get('expiry_date', now_time + DEFAULT_EXPIRY))
is_expired = expiry_date < now_time
# Check for minimum responses for creator
if current_responses < MINIMUM_RESPONSES:
if is_creator:
response = {
'status': 'incomplete',
'current_responses': current_responses,
'total_responses': current_responses,
'minimum_responses': MINIMUM_RESPONSES,
'remaining_responses': MINIMUM_RESPONSES - current_responses,
'is_creator': True,
'user_code': user_code,
'survey_id': survey_id,
'is_trending': is_trending,
'participant_bucket': participant_bucket,
'expiry_date': expiry_date.isoformat(),
'expired': is_expired
}
return jsonify(response), 200
else:
response = {
'status': 'incomplete',
'is_creator': False,
'is_trending': is_trending,
'participant_bucket': participant_bucket,
'expiry_date': expiry_date.isoformat(),
'expired': is_expired
}
return jsonify(response), 202
# Calculate statistics
results = calculate_survey_statistics(survey, answers, user_code, is_creator)
results['is_trending'] = is_trending
results['participant_bucket'] = participant_bucket
results['expiry_date'] = expiry_date.isoformat()
results['expired'] = is_expired
return jsonify(results), 200
def calculate_survey_statistics(survey, answers, user_code, is_creator):
logging.info(f"Calculating statistics for survey {survey['survey_id']}, user_code {user_code}, is_creator: {is_creator}")
questions = {q['id']: q for q in survey['questions']}
now_time = datetime.datetime.now(datetime.UTC)
results = {
'survey_id': survey['survey_id'],
'title': survey['title'],
'description': survey.get('description', ''),
'created_at': survey['survey_id'],
'is_creator': is_creator,
'questions': [],
'overall_statistics': {},
'expiry_date': make_tz_aware(survey.get('expiry_date', now_time + DEFAULT_EXPIRY)).isoformat(),
'expired': make_tz_aware(survey.get('expiry_date', now_time + DEFAULT_EXPIRY)) < now_time,
'total_responses': len(answers)
}
creator_answers = {str(q['id']): q['creator_answer'] for q in survey['questions']}
user_answers = creator_answers if is_creator else next((a['answers'] for a in answers if str(a.get('user_code')) == str(user_code)), None)
logging.info(f"User answers: {user_answers}")
logging.info(f"Creator answers: {creator_answers}")
all_deviations = []
user_deviations = []
for q_id, question in questions.items():
q_answers = [a['answers'][str(q_id)] for a in answers if str(q_id) in a['answers']]
creator_answer = creator_answers.get(q_id)
avg_score = mean(q_answers) if q_answers else None
logging.info(f"Processing question ID: {q_id}")
logging.info(f"Question type: {question['response_type']}")
if question['response_type'] == 'scale':
try:
std_dev = stdev(q_answers) if len(q_answers) > 1 else 0
except StatisticsError:
std_dev = 0
q_stat = {
'id': q_id,
'text': question['text'],
'type': 'scale',
'scale_max': question['response_scale_max'],
'average_score': round(avg_score, 2) if avg_score is not None else None,
'standard_deviation': round(std_dev, 2),
'distribution': {score: q_answers.count(score) for score in range(1, question['response_scale_max'] + 1)}
}
if user_answers and str(q_id) in user_answers:
user_score = user_answers[str(q_id)]
q_stat['user_score'] = user_score
if avg_score is not None:
user_deviation = abs(user_score - avg_score)
q_stat['user_deviation'] = round(user_deviation, 2)
user_deviations.append(user_deviation)
# Calculate deviation from creator for all users, including creator
if creator_answer is not None:
creator_deviation = abs(user_score - creator_answer)
q_stat['deviation_from_creator'] = round(creator_deviation, 2)
# Calculate deviation from others
other_answers = q_answers if is_creator else [a for a in q_answers if a != user_score]
if other_answers:
other_avg = mean(other_answers)
other_deviation = abs(user_score - other_avg)
q_stat['deviation_from_others'] = round(other_deviation, 2)
# Calculate overall deviation for this question
if creator_answer is not None:
question_deviations = [abs(ans - creator_answer) for ans in q_answers]
all_deviations.extend(question_deviations)
elif question['response_type'] == 'boolean':
true_count = sum(q_answers)
total_count = len(q_answers)
q_stat = {
'id': q_id,
'text': question['text'],
'type': 'boolean',
'true_percentage': round(true_count / total_count * 100, 2) if total_count > 0 else 0,
'false_percentage': round((total_count - true_count) / total_count * 100, 2) if total_count > 0 else 0
}
if user_answers and str(q_id) in user_answers:
q_stat['user_answer'] = user_answers[str(q_id)]
results['questions'].append(q_stat)
# Calculate overall statistics
results['overall_statistics'] = {
'average_deviation_from_aggregate': round(mean(user_deviations), 2) if user_deviations else None,
'overall_deviation': round(mean(all_deviations), 2) if all_deviations else None,
}
# Remove None values from overall_statistics
results['overall_statistics'] = {k: v for k, v in results['overall_statistics'].items() if v is not None}
results['total_participants'] = len(answers)
logging.info(f"Final results: {results}")
return results
@app.errorhandler(404)
def not_found(error):
app.logger.warning(f"404 error: {request.url}")
return jsonify({'error': 'Not found'}), 404
@app.errorhandler(500)
def internal_error(error):
app.logger.error(f"500 error: {str(error)}")
return jsonify({'error': 'Internal server error'}), 500
if __name__ == '__main__':
app.logger.info("Starting the Flask application")
app.logger.info(f"Registered routes: {app.url_map}")
app.run(debug=False, host='0.0.0.0', port=5001)
================
File: docker-compose.yml
================
version: '3'
services:
nginx:
image: nginx:stable-alpine
ports:
- "80:80"
volumes: