-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
3643 lines (3077 loc) · 128 KB
/
app.py
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
from flask import (
Flask,
render_template,
url_for,
request,
redirect,
session,
jsonify,
Response,
json,
send_file,
send_from_directory,
make_response,
flash,
abort,
g
)
import re
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, desc, asc, and_, cast, Date
from flask_migrate import Migrate
from models import (
db,
User,
Project,
Vote,
Comment,
ProjectView,
Bookmark,
Report,
WebsiteViews,
Baustelle,
Question,
GeoJSONFeature
)
from flask_login import (
LoginManager,
UserMixin,
login_user,
logout_user,
login_required,
current_user,
)
from werkzeug.security import generate_password_hash, check_password_hash
from authlib.integrations.flask_client import OAuth
from werkzeug.utils import secure_filename
from datetime import datetime, timedelta, date
from werkzeug.middleware.proxy_fix import ProxyFix
from forms import RegistrationForm, LoginForm, CommentForm
from random import randint
from urllib.parse import quote, unquote
from markupsafe import Markup
from twilio.rest import Client
import matplotlib.pyplot as plt
from openpyxl import Workbook
import openpyxl
from openpyxl.drawing.image import Image as ExcelImage
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.chart import PieChart, Reference
from collections import Counter
from bs4 import BeautifulSoup
import logging
import shutil
from PIL import Image
from pathlib import Path
from collections import Counter
import os
import pandas as pd
import random
import string
import json
import uuid
import zipfile
import pytz
import io
import time
import threading
from io import StringIO
import random
from dotenv import load_dotenv
load_dotenv()
# Twilio credentials
account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
twilio_number = os.environ.get("TWILIO_PHONE_NUMBER")
# Initialize the Flask app
app = Flask(__name__)
app.wsgi_app = ProxyFix(
app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1
)
app.secret_key = "maybeMangoOtters"
oauth = OAuth(app)
# Configure the database
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project_voting.db"
# Define the UPLOAD_FOLDER
app.config[
"UPLOAD_FOLDER"
] = "static/usersubmissions" # Specify the folder where uploaded files will be saved
app.config['GEOJSON_FOLDER'] = 'static/usersubmissions/geojson'
app.config['BAUSTELLE_IMAGE_FOLDER'] = 'static/baustellepics'
db.init_app(app)
migrate = Migrate(app, db)
# Initialize Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
# Configure logging
logging.basicConfig(level=logging.DEBUG)
ip_last_posted = {}
ip_last_submitted_project = {}
ip_last_added_marker = {}
ip_marker_additions = {} # Initialize the dictionary to track marker additions
ip_project_submissions = {}
google = oauth.register(
"google",
client_id="FREELANCER",
client_secret="FREELANCER",
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": "openid email profile"},
)
@app.before_request
def before_request():
g.metaData = {
'og_url': 'https://www.stimmungskompass.at/',
'og_title': 'Stimmungskompass - Eine Plattform zur Bürgerbeteiligung',
'og_description': 'Eine Plattform zur Bürgerbeteiligung. Engagiere dich für eine bessere Stadt!',
'og_image': 'https://www.stimmungskompass.at/static/facebook_card.png'
}
@app.route('/get_questions/<int:baustelle_id>')
def get_questions(baustelle_id):
questions = Question.query.filter_by(baustelle_id=baustelle_id).all()
questions_data = [{
'id': question.id,
'text': question.text,
'author': question.author,
'date': question.date.isoformat(),
'answer_text': question.answer_text,
'answered': question.answered,
'baustelle_id': question.baustelle_id,
'latitude': question.latitude,
'longitude': question.longitude,
'answer_date': question.answer_date.isoformat() if question.answer_date else None, # Format answer_date
} for question in questions]
return jsonify(questions_data)
@app.route('/answer_question/<int:question_id>', methods=['POST'])
@login_required
def answer_question(question_id):
if current_user.id != 1:
return jsonify({'error': 'Unauthorized', 'success': False}), 403
data = request.get_json()
if not data or 'answer_text' not in data:
return jsonify({'error': 'Missing answer text', 'success': False}), 400
question = Question.query.get_or_404(question_id)
question.answer_text = data['answer_text']
question.answered = True
question.answer_date = datetime.utcnow()
db.session.commit()
return jsonify({'message': 'Question answered successfully', 'success': True}), 200
@app.route('/delete_question/<int:question_id>', methods=['DELETE'])
@login_required # Assuming you're using Flask-Login for user management
def delete_question(question_id):
question = Question.query.get_or_404(question_id)
db.session.delete(question)
db.session.commit()
return jsonify({'message': 'Question successfully deleted'}), 200
@app.route('/delete_baustelle/<int:baustelle_id>', methods=['DELETE'])
@login_required # Assuming you're using Flask-Login for user management
def delete_baustelle(baustelle_id):
baustelle = Baustelle.query.get_or_404(baustelle_id)
db.session.delete(baustelle)
db.session.commit()
return jsonify({'message': 'Baustelle successfully deleted'}), 200
@app.route('/admin/neuebaustelle', methods=['GET', 'POST'])
def neuebaustelle():
if request.method == 'POST':
name = request.form.get('name')
description = request.form.get('description')
gis_data_str = request.form.get('gis_data')
gisfiles = request.form.get('gisfiles')
for file in request.files.getlist('gis_data[]'):
app.logger.debug(file)
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['GEOJSON_FOLDER'], filename))
gis_data = json.loads(gis_data_str) if gis_data_str else None
image = request.files.get('projectImage')
image_path = None
imagename = None
if image and image.filename:
filename = secure_filename(image.filename)
imagename = filename
image_path = os.path.join(app.config['BAUSTELLE_IMAGE_FOLDER'],filename)
app.logger.debug(image_path)
image.save(image_path)
new_baustelle = Baustelle(name=name, description=description, gis_data=gis_data, gisfile=gisfiles, author="Author Name", image=imagename)
db.session.add(new_baustelle)
db.session.commit()
return jsonify({'status': 'success', 'message': 'Baustelle created successfully.','gisfile':gisfiles, 'baustelleId': new_baustelle.id})
else:
return render_template('neuebaustelle.html')
def allowed_file(filename):
# Implement your file validation logic here
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
ALLOWED_EXTENSIONS = {'geojson'}
@app.route('/baustellen/<int:baustelle_id>', methods=['GET', 'POST'])
def baustellen(baustelle_id):
# Check user authentication and admin status
is_admin = False
user_id = None
if current_user.is_authenticated:
user_id = current_user.id
is_admin = current_user.is_admin or user_id == 1
# Retrieve the specified Baustelle by its ID
baustelle = Baustelle.query.get_or_404(baustelle_id)
gisfile = baustelle.gisfile
gis_data = baustelle.gis_data
image = baustelle.image
# Handle POST request: Adding a new question to the Baustelle
if request.method == 'POST':
# Retrieve the question text from form data
text = request.form.get('text')
if text:
# Create a new Question instance and add it to the database
question = Question(text=text, baustelle_id=baustelle_id, author_id=current_user.id) # Assuming each Question has an author
db.session.add(question)
db.session.commit()
flash('Ihre Frage wurde hinzugefügt.', 'success')
else:
flash('Die Frage darf nicht leer sein.', 'warning')
# Redirect back to the same Baustelle page to display the new question
return redirect(url_for('baustellen', baustelle_id=baustelle_id))
# For a GET request or after handling the POST request, render the Baustelle page
# Retrieve all questions associated with this Baustelle
questions = Question.query.filter_by(baustelle_id=baustelle_id).all()
return render_template('baustellen.html', baustelle=baustelle, is_admin=is_admin, user_id=user_id, questions=questions,gisfile=gisfile, gis_data=gis_data)
@app.context_processor
def inject_newest_baustelle_id():
newest_baustelle = Baustelle.query.order_by(Baustelle.id.desc()).first()
newest_baustelle_id = newest_baustelle.id if newest_baustelle else None
return {'newest_baustelle_id': newest_baustelle_id}
@app.route('/submit_question', methods=['POST'])
def submit_question():
data = request.get_json()
new_question = Question(
text=data['text'],
author=data.get('author', 'Anonymous'),
baustelle_id=int(data['baustelle_id']),
latitude=data['latitude'],
longitude=data['longitude'],
date=datetime.utcnow(),
)
db.session.add(new_question)
db.session.commit()
return jsonify({
'id': new_question.id,
'text': new_question.text,
'author': new_question.author,
'baustelle_id': new_question.baustelle_id,
'date': new_question.date.isoformat(),
'latitude': new_question.latitude,
'longitude': new_question.longitude,
}), 201
@app.route('/images/<path:filename>')
def serve_image(filename):
image_dir = os.path.join(app.root_path, 'static')
image_path = os.path.join(image_dir, filename)
if 'image/webp' in request.headers.get('Accept', ''):
webp_path = os.path.splitext(image_path)[0] + '.webp'
if not os.path.exists(webp_path):
os.makedirs(os.path.dirname(webp_path), exist_ok=True)
try:
with Image.open(image_path) as img:
# Adjust the quality parameter here (e.g., quality=75 for 75% quality)
img.save(webp_path, 'WEBP', quality=75)
except IOError:
abort(404) # Image not found or unable to convert
return send_from_directory(os.path.dirname(webp_path), os.path.basename(webp_path), mimetype='image/webp')
else:
return send_from_directory(os.path.dirname(image_path), os.path.basename(filename))
@app.route("/log_view")
def log_view():
ip_address = request.remote_addr # Get the IP address of the visitor
# Check if this IP address has already been logged today
existing_view = WebsiteViews.query.filter_by(
view_date=datetime.utcnow().date(), ip_address=ip_address
).first()
unique_views_count = WebsiteViews.query.filter_by(
view_date=datetime.utcnow().date()
).count()
if existing_view:
# IP address has already been logged today
return (
jsonify(
{
"message": f"IP {ip_address} not logged, it has already been logged today. There are {unique_views_count} unique viewers today."
}
),
200,
)
else:
WebsiteViews.add_view(ip_address)
print(f"New view logged for IP {ip_address}") # Debugging
return (
jsonify(
{
"message": f"IP {ip_address} logged. It is today the {unique_views_count + 1}th viewer."
}
),
200,
)
@app.route("/get_unique_viewers_data")
def get_unique_viewers_data():
try:
start_date = request.args.get(
"start_date", (datetime.utcnow() - timedelta(days=6)).strftime("%Y-%m-%d")
)
end_date = request.args.get("end_date", datetime.utcnow().strftime("%Y-%m-%d"))
# Convert string dates to datetime.date objects
start_date_obj = datetime.strptime(start_date, "%Y-%m-%d").date()
end_date_obj = datetime.strptime(end_date, "%Y-%m-%d").date()
unique_viewers_data = (
db.session.query(
WebsiteViews.view_date,
func.count(WebsiteViews.ip_address).label("viewer_count"),
)
.filter(WebsiteViews.view_date.between(start_date_obj, end_date_obj))
.group_by(WebsiteViews.view_date)
.all()
)
print("Queried Data:", unique_viewers_data) # Debugging
viewer_count_dict = {
view_date.strftime("%Y-%m-%d"): viewer_count
for view_date, viewer_count in unique_viewers_data
}
labels, values = zip(
*[
(
date.strftime("%Y-%m-%d"),
viewer_count_dict.get(date.strftime("%Y-%m-%d"), 0),
)
for date in (
start_date_obj + timedelta(n)
for n in range((end_date_obj - start_date_obj).days + 1)
)
]
)
return jsonify({"labels": labels, "values": values})
except Exception as e:
print("Error:", str(e)) # More detailed error logging
return jsonify({"error": str(e)}), 500
@app.route("/get_unique_viewers_data_range", methods=["POST"])
def get_unique_viewers_data_range():
try:
# Extract start and end dates from the request
data = request.get_json()
start_date = datetime.strptime(data["start_date"], "%Y-%m-%d").date()
end_date = datetime.strptime(data["end_date"], "%Y-%m-%d").date()
print("Startdatum:", start_date, "Enddatum:", end_date) # Debugging
# Query for viewer counts between the specified dates
unique_viewers_data = (
db.session.query(
WebsiteViews.view_date,
func.count(WebsiteViews.ip_address).label("viewer_count"),
)
.filter(WebsiteViews.view_date.between(start_date, end_date))
.group_by(WebsiteViews.view_date)
.all()
)
print("Queried Data:", unique_viewers_data) # Debugging
viewer_count_dict = {
view_date.strftime("%Y-%m-%d"): viewer_count
for view_date, viewer_count in unique_viewers_data
}
labels, values = zip(
*[
(
date.strftime("%Y-%m-%d"),
viewer_count_dict.get(date.strftime("%Y-%m-%d"), 0),
)
for date in (
start_date + timedelta(n)
for n in range((end_date - start_date).days + 1)
)
]
)
return jsonify({"labels": labels, "values": values})
except Exception as e:
print("Error:", str(e)) # More detailed error logging
return jsonify({"error": str(e)}), 500
@app.route("/project_submission_stats")
def project_submission_stats():
try:
start_date = request.args.get(
"start", (date.today() - timedelta(days=7)).isoformat()
)
end_date = request.args.get("end", date.today().isoformat())
include_map_objects = request.args.get("includeMapObjects") == "true"
exclude_map_objects = request.args.get("excludeMapObjects") == "true"
app.logger.debug(
f"Fetching stats from {start_date} to {end_date}, include Notizens: {include_map_objects}, exclude Notizens: {exclude_map_objects}"
)
query = db.session.query(
func.strftime("%Y-%m-%d", Project.date).label("submission_date"),
Project.category,
func.count(Project.id).label("project_count"),
).filter(Project.date.between(start_date, end_date))
if include_map_objects:
query = query.filter(Project.is_mapobject == True)
elif exclude_map_objects:
query = query.filter(Project.is_mapobject == False)
submission_stats = query.group_by("submission_date", Project.category).all()
app.logger.debug(f"Raw data: {submission_stats}")
categories = set(category for _, category, _ in submission_stats)
stats = {category: {} for category in categories}
for submission_date, category, project_count in submission_stats:
stats[category][submission_date] = project_count
app.logger.debug(f"Processed stats: {stats}")
return jsonify(stats)
except Exception as e:
app.logger.error(f"Error in project_submission_stats: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/get_activity_data")
def get_activity_data():
start_date = request.args.get(
"start", (date.today() - timedelta(days=7)).isoformat()
)
end_date = request.args.get("end", date.today().isoformat())
# Fetching upvotes, downvotes, and comments
upvotes = (
db.session.query(
func.date(Vote.timestamp).label("date"), func.count().label("count")
)
.filter(Vote.timestamp.between(start_date, end_date), Vote.upvote == True)
.group_by(func.date(Vote.timestamp))
.all()
)
downvotes = (
db.session.query(
func.date(Vote.timestamp).label("date"), func.count().label("count")
)
.filter(Vote.timestamp.between(start_date, end_date), Vote.downvote == True)
.group_by(func.date(Vote.timestamp))
.all()
)
comments = (
db.session.query(
func.date(Comment.timestamp).label("date"), func.count().label("count")
)
.filter(Comment.timestamp.between(start_date, end_date))
.group_by(func.date(Comment.timestamp))
.all()
)
# Fetching reports
reports = (
db.session.query(
func.date(Report.timestamp).label("date"), func.count().label("count")
)
.filter(Report.timestamp.between(start_date, end_date))
.group_by(func.date(Report.timestamp))
.all()
)
# Fetching bookmarks
bookmarks = (
db.session.query(
func.date(Bookmark.timestamp).label("date"), func.count().label("count")
)
.filter(Bookmark.timestamp.between(start_date, end_date))
.group_by(func.date(Bookmark.timestamp))
.all()
)
# Convert query results to dictionaries
upvotes_dict = {str(day.date): day.count for day in upvotes}
downvotes_dict = {str(day.date): day.count for day in downvotes}
comments_dict = {str(day.date): day.count for day in comments}
reports_dict = {str(day.date): day.count for day in reports}
bookmarks_dict = {str(day.date): day.count for day in bookmarks}
activity_data = {
"upvotes": upvotes_dict,
"downvotes": downvotes_dict,
"comments": comments_dict,
"reports": reports_dict,
"bookmarks": bookmarks_dict,
}
return jsonify(activity_data)
@app.route("/get_view_data")
def get_view_data():
start_date = request.args.get(
"start", (datetime.today() - timedelta(days=7)).strftime("%Y-%m-%d")
)
end_date = request.args.get("end", datetime.today().strftime("%Y-%m-%d"))
daily_views = (
db.session.query(
func.date(Project.date).label("date"),
func.sum(Project.view_count).label("daily_view_count"),
)
.filter(Project.date.between(start_date, end_date))
.group_by(func.date(Project.date))
.all()
)
total_views = (
db.session.query(func.sum(Project.view_count))
.filter(Project.date.between(start_date, end_date))
.scalar()
)
daily_views_dict = {str(day.date): day.daily_view_count for day in daily_views}
view_data = {"daily_views": daily_views_dict, "total_views": total_views}
return jsonify(view_data)
@app.route("/get_engaged_projects")
@login_required
def get_engaged_projects():
threshold = request.args.get("threshold", default=1, type=int)
# Query projects with view_count greater than or equal to threshold
projects = Project.query.filter(Project.view_count >= threshold).all()
project_list = []
for project in projects:
project_details = {
"id": project.id,
"name": project.name,
"category": project.category, # Include the category here
"views": project.view_count,
"upvotes": len([vote for vote in project.votes if vote.upvote]),
"downvotes": len([vote for vote in project.votes if vote.downvote]),
"comments": len(project.comments),
"bookmarks": len(Bookmark.query.filter_by(project_id=project.id).all()),
"reports": project.p_reports,
}
project_list.append(project_details)
return jsonify(project_list)
@app.route("/get_chart_data", methods=["GET"])
@login_required
def get_chart_data():
filter_param = request.args.get("filter", "all")
description_length_filter = request.args.get("description_length_filter", "all")
projects_query = Project.query
description_projects_query = Project.query
if filter_param == "true":
projects_query = projects_query.filter_by(is_mapobject=True)
elif filter_param == "false":
projects_query = projects_query.filter_by(is_mapobject=False)
if description_length_filter == "true":
description_projects_query = description_projects_query.filter_by(
is_mapobject=True
)
elif description_length_filter == "false":
description_projects_query = description_projects_query.filter_by(
is_mapobject=False
)
# Count projects per category with the filtered query
category_counts = (
projects_query.with_entities(Project.category, func.count(Project.id))
.group_by(Project.category)
.all()
)
category_counts = {category: count for category, count in category_counts}
# Count Notizens vs Projektvorschläge
mapobject_counts = {
"Notizen": Project.query.filter_by(is_mapobject=True).count(),
"Projektvorschläge": Project.query.filter_by(is_mapobject=False).count(),
}
description_length_ranges = ["0-50", "51-100", "101-150", "151-200", ">200"]
description_length_counts = {range: 0 for range in description_length_ranges}
total_description_length = 0
description_projects_count = description_projects_query.count()
for project in description_projects_query:
length = len(project.descriptionwhy)
total_description_length += length
if length <= 50:
description_length_counts["0-50"] += 1
elif 51 <= length <= 100:
description_length_counts["51-100"] += 1
elif 101 <= length <= 150:
description_length_counts["101-150"] += 1
elif 151 <= length <= 200:
description_length_counts["151-200"] += 1
else:
description_length_counts[">200"] += 1
average_description_length = (
(total_description_length / description_projects_count)
if description_projects_count > 0
else 0
)
return jsonify(
{
"categoryCounts": category_counts,
"mapobjectCounts": mapobject_counts,
"descriptionLengthCounts": description_length_counts,
"averageDescriptionLength": average_description_length,
}
)
def get_project_category_chart_data():
# Count projects per category
projects = Project.query.all()
category_counts = Counter([project.category for project in projects])
# Prepare data for the pie chart
pie_chart_data = {
"labels": list(category_counts.keys()),
"datasets": [
{
"label": "Project Categories",
"data": list(category_counts.values()),
"backgroundColor": [
"#ff6384",
"#36a2eb",
"#cc65fe",
"#ffce56",
"#4bc0c0",
"#f77825",
], # Customize colors
}
],
}
return pie_chart_data
@app.route("/login/google")
def google_login():
# Generate a nonce and store it in the session
nonce = "".join(random.choices(string.ascii_uppercase + string.digits, k=16))
session["google_auth_nonce"] = nonce
redirect_uri = url_for("authorized", _external=True)
return oauth.google.authorize_redirect(
redirect_uri, nonce=nonce, prompt="select_account"
)
def generate_pie_chart_categories(workbook, categories):
logging.debug("Generating pie chart for categories")
pie_sheet = workbook.create_sheet(title="Categories Pie Chart")
for row in categories.items():
pie_sheet.append(row)
chart = PieChart()
labels = Reference(pie_sheet, min_col=1, min_row=2, max_row=len(categories) + 1)
data = Reference(pie_sheet, min_col=2, min_row=1, max_row=len(categories) + 1)
chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)
pie_sheet.add_chart(chart, "E2")
# Function to generate pie chart for description lengths
def generate_pie_chart_description_length(workbook, length_ranges):
logging.debug("Generating pie chart for description lengths")
pie_sheet = workbook.create_sheet(title="Description Lengths Pie Chart")
for row in length_ranges.items():
pie_sheet.append(row)
chart = PieChart()
labels = Reference(pie_sheet, min_col=1, min_row=2, max_row=len(length_ranges) + 1)
data = Reference(pie_sheet, min_col=2, min_row=1, max_row=len(length_ranges) + 1)
chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)
pie_sheet.add_chart(chart, "E2")
def calculate_votes(project_id):
project = Project.query.get(project_id)
if project:
upvotes = Vote.query.filter_by(project_id=project.id, upvote=True).count()
downvotes = Vote.query.filter_by(project_id=project.id, downvote=True).count()
# upvotes = sum(1 for vote in project.votes if vote.upvote)
# downvotes = sum(1 for vote in project.votes if vote.downvote)
return upvotes, downvotes
else:
return 0, 0
@app.route("/export_gis", methods=["GET"])
@login_required
def export_gis():
category = request.args.get("category", "")
if category and category != "Alle Kategorien":
projects = Project.query.filter_by(category=category).all()
else:
projects = Project.query.all()
features = []
for project in projects:
if project.geoloc and "," in project.geoloc:
lat, lon = project.geoloc.split(",")
try:
lat, lon = float(lat.strip()), float(lon.strip())
features.append(
{
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [lon, lat]},
"properties": project.to_dict(),
}
)
except ValueError:
pass # Handle invalid geolocation data
geojson_data = {"type": "FeatureCollection", "features": features}
formatted_geojson = json.dumps(geojson_data, indent=4)
response = Response(
formatted_geojson,
mimetype="application/json",
headers={"Content-Disposition": "attachment;filename=exported_data.geojson"},
)
return response
@app.route("/export_csv", methods=["GET", "POST"])
@login_required
def export_csv():
category = request.args.get("category", "")
# Querying the database based on the category
if category and category != "Alle Kategorien":
projects_data = Project.query.filter_by(category=category).all()
else:
projects_data = Project.query.all()
projects_list = [project.to_dict() for project in projects_data]
# Convert to DataFrame
df = pd.DataFrame(projects_list)
# Converting DataFrame to CSV
csv_data = StringIO()
df.to_csv(csv_data, index=False)
# Flask response
response = make_response(csv_data.getvalue())
response.headers["Content-Disposition"] = "attachment; filename=projects_data.csv"
response.headers["Content-type"] = "text/csv"
return response
@app.route("/export_questions", methods=["GET", "POST"])
def export_questions():
try:
questions = Question.query.all()
app.logger.info(questions)
questions_data = []
for question in questions:
app.logger.info(question)
question_dict = question.to_dict()
questions_data.append(question_dict)
df = pd.DataFrame(questions_data)
rename_columns = {
"id": "ID",
"text": "Text",
"author": "Author",
"date": "Date",
"answer_text": "Answer Text",
"answered": "Answered",
"baustelle_id": "Baustelle ID",
"latitude": "Latitude",
"longitude": "Longitude",
"answer_date":"Answer Date"
}
df = df.rename(columns=rename_columns)[
list(rename_columns.values())
] # Reorder columns
app.logger.info(df.to_json)
app.logger.info(questions)
filename = "exported_questions.xlsx"
filepath = os.path.join("static/excel", filename)
writer = pd.ExcelWriter(filepath, engine="openpyxl")
df.to_excel(writer, index=False, sheet_name="Exported Projects")
workbook = writer.book
worksheet = writer.sheets["Exported Projects"]
# Medium border style
medium_border_side = Side(border_style="medium", color="000000")
medium_border = Border(top=medium_border_side, bottom=medium_border_side)
font_size = 12
bahnschrift_font = Font(name="Bahnschrift", size=font_size)
header_font = Font(
name="Bahnschrift", bold=True, color="F5F1E4", size=font_size + 2
)
header_fill = PatternFill(
start_color="003056", end_color="003056", fill_type="solid"
)
for row in worksheet.iter_rows(
min_row=2, min_col=2, max_col=2
): # Kategorie is the 2nd column
for cell in row:
cell.font = Font(name="Bahnschrift", size=12, bold=True)
for row in worksheet.iter_rows():
for cell in row:
cell.font = bahnschrift_font # Set font for all cells
cell.border = medium_border # Set medium border for all cells
if cell.row == 1:
cell.font = header_font # Override font for the first row
cell.fill = header_fill # Apply fill for the first row
cell.alignment = Alignment(horizontal="center", vertical="center")
colors = ["F5F1E4", "D9D4C7"]
for i, column_cells in enumerate(worksheet.columns):
color_index = i % len(colors) # Alternate between 0 and 1
fill = PatternFill(
start_color=colors[color_index],
end_color=colors[color_index],
fill_type="solid",
)
for cell in column_cells[1:]: # Skip the first row
cell.fill = fill
cell.alignment = Alignment(wrap_text=True)
# Adjust column widths based on the longest content
max_char_length = 50
for column_cells in worksheet.columns:
length = max(len(str(cell.value)) for cell in column_cells)
length = min(length, max_char_length) # Limit to max_char_length characters
col_width = length * 1.3 # Approximate column width
column_letter = get_column_letter(column_cells[0].column)
worksheet.column_dimensions[column_letter].width = col_width
# Pie Chart for Project Categories
start_row_for_charts = df.shape[0] + 3
writer._save()
app.logger.debug(f"Excel file with pie charts saved at {filepath}")
return jsonify({"states": filepath})
except Exception as e:
print("Error:", str(e)) # More detailed error logging
return jsonify({"error": str(e)}), 500
@app.route("/export_projects", methods=["GET", "POST"])
@login_required
def export_projects():
try:
category = request.values.get("category")
include_comments = "include_comments" in request.values
include_votes = "include_votes" in request.values
query = Project.query
if category:
query = query.filter_by(category=category)
projects = query.all()
# Convert to DataFrame and strip HTML tags from specific fields
def strip_html(content):
if content:
return BeautifulSoup(content, "html.parser").get_text()
return content
projects_data = []
for project in projects:
app.logger.info(project)
project_dict = project.to_dict()
# Update fields with HTML content
project_dict["descriptionwhy"] = strip_html(project_dict["descriptionwhy"])
project_dict["public_benefit"] = strip_html(
project_dict["public_benefit"]
) # Apply to 'public_benefit'
# Calculate upvotes and downvotes
upvotes, downvotes = calculate_votes(project.id)
print(
f"Project ID {project.id} exported with {upvotes} upvotes and {downvotes} downvotes into the Excel table"
)
project_dict["upvotes"] = upvotes
project_dict["downvotes"] = downvotes
projects_data.append(project_dict)
df = pd.DataFrame(projects_data)
rename_columns = {
"id": "ID",
"category": "Kategorie",
"name": "Titel",
"descriptionwhy": "Beschreibung",
"public_benefit": "Vorteile",
"date": "Datum",
"geoloc": "Markierter Standort",
"author": "Author",
"image_file": "Bild",
"is_important": "Privat markiert",
"is_featured": "Ausgewählt",
"view_count" : "View Count",
"p_reports" : "P Reports",
"upvotes": "Upvotes", # New columns for upvotes and downvotes
"downvotes": "Downvotes",
}
df = df.rename(columns=rename_columns)[
list(rename_columns.values())
] # Reorder columns
app.logger.info(df.to_json)
app.logger.info(projects)