-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1706 lines (1498 loc) · 62.9 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 datetime import datetime # For handling dates and times
from flask import Flask, jsonify, render_template, request # For creating the Flask app and returning JSON responses
from pymongo import MongoClient # For connecting to MongoDB
# Initialize Flask app
app = Flask(__name__, template_folder='data_visualization/templates', static_folder='data_visualization/static')
# Initialize MongoDB client and specify the database and collection
client = MongoClient('mongodb://localhost:27017/')
db = client['Almayadeen']
collection = db['articles']
# Define the routes for the dashboard and the API endpoints
@app.route('/')
def dashboard():
return render_template('dashboard.html')
# Advanced text analysis routes
# 1. Route for getting articles by entity
@app.route('/articles_by_entity', methods=['GET'])
def articles_by_entity():
"""
This route handles a GET request to '/articles_by_entity'. It runs an aggregation pipeline on the 'articles' collection
to find and return articles that mention the specified entity (in MISC, LOC, PERS, or ORG fields).
"""
# Get the entity from the query parameters
entity = request.args.get('entity','القدس') # Default to 'القدس' if not provided
if not entity:
return jsonify({"error": "Please provide an entity to search for."}), 400
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match articles where the entity is in MISC, LOC, PERS, or ORG fields
{
"$match": {
"$or": [
{"entities.MISC": entity}, # Match in MISC entities
{"entities.LOC": entity}, # Match in LOC entities
{"entities.PERS": entity}, # Match in PERS entities
{"entities.ORG": entity} # Match in ORG entities
]
}
},
# Stage 2: Project the desired fields
{
"$project": {
"_id": 0, # Exclude the '_id' field
"title": 1, # Include the article title
"url": 1, # Include the article URL
"entities": 1 # Include the entities field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/articles_by_entity.html', data=result, default_entity=entity)
# 2. Route for getting articles by sentiment
@app.route('/articles_by_sentiment', methods=['GET'])
def articles_by_sentiment():
"""
This route handles requests to '/articles_by_sentiment'.
It returns articles that match the specified sentiment ('positive', 'negative', 'neutral').
"""
# Set a default sentiment if not provided
sentiment = request.args.get('sentiment', 'positive').lower()
if sentiment.lower() not in ['positive', 'negative', 'neutral']:
return jsonify({"error": "Invalid sentiment. Choose from positive, negative, or neutral."}), 400
# Define the aggregation pipeline to fetch articles with the specified sentiment
pipeline = [
{"$match": {"sentiment": sentiment}}, # Match articles based on sentiment
{"$project": {"title": 1, "full_text": 1, "sentiment": 1, "sentiment_score" : 1, "_id": 0}} # Only include title, full_text, and sentiment
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Return JSON if requested, otherwise render an HTML template
if request.args.get('format') == 'json':
return jsonify(result)
else:
return render_template('visualizations/articles_by_sentiment.html', data=result, default_sentiment=sentiment)
# 3. Route for getting articles by sentiment trend
@app.route('/sentiment_trends', methods=['GET'])
def sentiment_trends():
"""
This route fetches sentiment trends over time, grouped by month and sentiment type.
"""
# Define the pipeline to aggregate sentiment trends by month
pipeline = [
# Stage 1: Convert the string date (published_time) to a date object
{
"$addFields": {
"published_date": {
"$dateFromString": {
"dateString": "$published_time"
}
}
}
},
# Stage 2: Group by month, year, and sentiment (or other fields)
{
"$group": {
"_id": {
"month": {"$month": "$published_date"},
"year": {"$year": "$published_date"},
"sentiment": "$sentiment"
},
"count": {"$sum": 1}
}
},
# Stage 3: Sort the result by year and month
{
"$sort": {"_id.year": 1, "_id.month": 1}
}
]
# Run the aggregation on the collection
result = list(collection.aggregate(pipeline))
# Return JSON if requested
if request.args.get('format') == 'json':
return jsonify(result)
else:
return render_template('visualizations/sentiment_trends.html', data=result)
# 4. Route for getting keyword trends over time
@app.route('/keyword_trends', methods=['GET'])
def keyword_trends():
"""
This route fetches keyword trends over time, grouped by month and keyword.
"""
# Get month, year, and keyword from request arguments
month = request.args.get('month', type=int)
year = request.args.get('year', type=int)
keyword = request.args.get('keyword', None) # Optional keyword filter
# Define the pipeline to aggregate keyword trends
pipeline = [
{ "$unwind": "$keywords" },
{
"$addFields": {
"published_date": {
"$dateFromString": {
"dateString": "$published_time"
}
}
}
},
{
"$match": {
"$expr": {
"$and": [
{ "$eq": [{ "$month": "$published_date" }, month] },
{ "$eq": [{ "$year": "$published_date" }, year] }
]
}
}
}
]
# Add keyword filter if provided
if keyword:
pipeline.append({
"$match": {
"keywords": keyword
}
})
# Group by keyword and count occurrences
pipeline.append({
"$group": {
"_id": {
"month": { "$month": "$published_date" },
"year": { "$year": "$published_date" },
"keyword": "$keywords"
},
"count": { "$sum": 1 }
}
})
pipeline.append({ "$sort": { "count": -1, "_id.year": 1, "_id.month": 1 } })
result = list(collection.aggregate(pipeline))
if request.args.get('format') == 'json':
return jsonify(result)
else:
return render_template('visualizations/keyword_trends.html', data=result)
# 5. Route for getting most positive articles
@app.route('/most_positive_articles', methods=['GET'])
def most_positive_articles():
"""
Fetch articles with the highest sentiment scores that are also labeled as positive.
"""
pipeline = [
{
"$match": {
"sentiment": "positive", # Ensure sentiment label is positive
"sentiment_score": {"$exists": True} # Ensure sentiment_score exists
}
},
{
"$sort": {
"sentiment_score": -1 # Sort by sentiment score descending
}
},
{
"$limit": 10 # Limit to top 10 articles
},
{
"$project": {
"_id": 0,
"title": 1,
"url": 1,
"sentiment": 1, # Include the sentiment field
"sentiment_score": 1, # Include the sentiment score
"published_time": 1
}
}
]
result = list(collection.aggregate(pipeline))
if request.args.get('format') == 'json':
return jsonify(result)
else:
return render_template('visualizations/most_positive_articles.html', data=result)
# 6. Route for getting most negative articles
@app.route('/most_negative_articles', methods=['GET'])
def most_negative_articles():
"""
Fetch articles with the lowest sentiment scores.
"""
pipeline = [
{
"$match": {
"sentiment": "negative", # Ensure sentiment label is negative
"sentiment_score": {"$exists": True} # Ensure sentiment_score exists
}
},
{"$sort": {"sentiment_score": -1}},
{"$limit": 10}, # Limit to top 10 articles
{"$project": {
"_id": 0,
"title": 1,
"url": 1,
"sentiment": 1, # Include the sentiment field
"sentiment_score": 1, # Include the sentiment score
"published_time": 1
}}
]
result = list(collection.aggregate(pipeline))
if request.args.get('format') == 'json':
return jsonify(result)
else:
return render_template('visualizations/most_negative_articles.html', data=result)
######################################################################################################################
# 1. Route for getting top keywords
@app.route('/top_keywords', methods=['GET'])
def top_keywords():
"""
This route handles a GET request to '/top_keywords'. It runs an aggregation pipeline on the 'articles' collection
to find and return the top 10 most frequent keywords across all documents in the collection.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Unwind the 'keywords' array, creating a document for each keyword
{"$unwind": "$keywords"},
# Stage 2: Group by the 'keywords' field and count the occurrences of each keyword
{
"$group": {
"_id": "$keywords", # Group by the keyword
"count": {"$sum": 1} # Count occurrences of each keyword
}
},
# Stage 3: Sort the groups by count in descending order
{"$sort": {"count": -1}},
# Stage 4: Limit the result to the top 10 keywords
{"$limit": 10},
# Stage 5: Project the results, renaming '_id' to 'keyword' and keeping the 'count'
{
"$project": {
"keyword": "$_id", # Rename '_id' to 'keyword'
"count": 1, # Include the 'count' field
"_id": 0 # Exclude the original '_id' field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template with a chart
return render_template('visualizations/top_keywords.html', data=result)
# 2. Route for getting top authors
@app.route('/top_authors', methods=['GET'])
def top_authors():
"""
This route handles a GET request to '/top_authors'. It runs an aggregation pipeline on the 'articles' collection
to find and return the top 10 authors who have written the most articles.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Group documents by the 'author' field and count the number of articles for each author
{
"$group": {
"_id": "$author", # Group by the 'author' field
"count": {"$sum": 1} # Count the number of articles for each author
}
},
# Stage 2: Sort the authors by the count of articles in descending order
{
"$sort": {"count": -1}
},
# Stage 3: Limit the result to the top 10 authors
{
"$limit": 10
},
# Stage 4: Project the results to show the 'author' and 'count' fields, excluding the default '_id' field
{
"$project": {
"_id": 0, # Exclude the default '_id' field from the output
"author": "$_id", # Rename '_id' to 'author'
"count": 1 # Include the 'count' field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template with a chart
return render_template('visualizations/top_authors.html', data=result)
# 3. Route for getting articles by publication date
@app.route('/articles_by_date', methods=['GET'])
def articles_by_date():
"""
This route handles a GET request to '/articles_by_date'. It runs an aggregation pipeline on the 'articles' collection
to group articles by their publication date and return the count of articles for each date.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Convert the 'published_time' to a date string in the format YYYY-MM-DD
{
"$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d", # Format the date as YYYY-MM-DD
"date": {
"$dateFromString": {
"dateString": "$published_time" # Convert the 'published_time' string to a date object
}
}
}
},
"count": {"$sum": 1} # Count the number of articles for each date
}
},
# Stage 2: Sort the grouped results by date in ascending order
{
"$sort": {
"_id": 1 # Sort by the date string in ascending order
}
},
# Stage 3: Project the results to include 'date' and 'count', excluding the default '_id' field
{
"$project": {
"_id": 0, # Exclude the default '_id' field from the output
"date": "$_id", # Rename '_id' to 'date'
"count": 1 # Include the 'count' field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template with a chart
return render_template('visualizations/articles_by_date.html', data=result)
# 4. Route for getting articles by word count
@app.route('/articles_by_word_count', methods=['GET'])
def articles_by_word_count():
"""
This route handles a GET request to '/articles_by_word_count'. It runs an aggregation pipeline on the 'articles' collection
to group the articles by word count and return the number of articles for each word count, sorted by word count.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Group by 'word_count' and count the number of articles for each word count
{
"$group": {
"_id": "$word_count", # Group by word count
"count": {"$sum": 1} # Count the number of articles for each word count
}
},
# Stage 2: Sort the results by word count in ascending order
{
"$sort": {
"_id": 1 # Sort by word count (ascending)
}
},
# Stage 3: Project the results to show 'word_count' instead of '_id' and include the 'count'
{
"$project": {
"word_count": "$_id", # Rename '_id' to 'word_count'
"count": 1, # Include the count
"_id": 0 # Exclude '_id'
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template with a chart
return render_template('visualizations/articles_by_word_count.html', data=result)
# 5. Route for getting articles by language
@app.route('/articles_by_language', methods=['GET'])
def articles_by_language():
"""
This route handles a GET request to '/articles_by_language'. It runs an aggregation pipeline on the 'articles' collection
to find and return the number of articles available in each language.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Group by the 'lang' field and count the number of articles for each language
{
"$group": {
"_id": "$lang", # Group by the language field
"count": {"$sum": 1} # Count the number of articles for each language
}
},
# Stage 2: Optionally project the results to rename '_id' to 'language'
{
"$project": {
"language": "$_id", # Rename '_id' to 'language'
"count": 1, # Keep the 'count' field
"_id": 0 # Exclude the original '_id' field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template with a chart
return render_template('visualizations/articles_by_language.html', data=result)
# 6. Route for getting articles by classes
@app.route('/articles_by_classes', methods=['GET'])
def articles_by_classes():
"""
This route handles a GET request to '/articles_by_classes'. It runs an aggregation pipeline on the 'articles' collection
to find and return the number of articles in each class, as specified in the 'classes' field.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Unwind the 'classes' array, creating a document for each class
{"$unwind": "$classes"},
# Stage 2: Match only documents where the 'mapping' field is 'category'
{
"$match": {
"classes.mapping": "category" # Ensure we match only the 'category' mapping
}
},
# Stage 3: Group by the 'classes.value' field and count the number of articles in each class
{
"$group": {
"_id": "$classes.value", # Group by the 'value' of the class with mapping 'category'
"count": {"$sum": 1} # Count the number of articles for each class value
}
},
# Stage 4: Project the results, renaming '_id' to 'class' and keeping the 'count'
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"class": "$_id", # Rename '_id' to 'class'
"count": 1 # Include the 'count' field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template with a chart
return render_template('visualizations/articles_by_classes.html', data=result)
# 7. Route for getting recent articles
@app.route('/recent_articles', methods=['GET'])
def recent_articles():
"""
This route handles a GET request to '/recent_articles'. It runs an aggregation pipeline on the 'articles' collection
to find and return the 10 most recently published articles.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Sort the articles by 'published_time' in descending order
{"$sort": {"published_time": -1}},
# Stage 2: Limit the result to the top 10 most recent articles
{"$limit": 10},
# Stage 3: Project the results to include necessary fields (e.g., title, published_time)
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"title": 1, # Include the title of the article
"published_time": 1 # Include the published time of the article
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/recent_articles.html', data=result)
# 8. Route for getting articles by keyword
@app.route('/articles_by_keyword', methods=['GET'])
def articles_by_keyword():
"""
This route handles a GET request to '/articles_by_keyword/<keyword>'. It runs an aggregation pipeline on the 'articles' collection
to find and return all articles that contain the specified keyword.
"""
# Get the keyword from the query parameters
keyword = request.args.get('keyword')
if keyword is None:
return render_template('visualizations/articles_by_keyword.html', data = [])
try:
# Check if the keyword is a valid string
keyword = str(keyword)
except ValueError:
# Return an error message if the keyword is not a valid string
return jsonify({"error": "Invalid keyword. Please provide a valid string."})
if keyword:
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match documents that contain the specified keyword in the 'keywords' array
{"$match": {"keywords": keyword}},
# Stage 2: Project the results to include necessary fields (e.g., title)
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"title": 1 # Include the title of the article
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Pass the result to the template
return render_template('visualizations/articles_by_keyword.html', data=result)
# 9. Route for getting articles by author
@app.route('/articles_by_author', methods=['GET'])
def articles_by_author():
"""
This route handles a GET request to '/articles_by_author/<author_name>'. It runs an aggregation pipeline on the 'articles' collection
to find and return all articles written by the specified author.
"""
author_name = request.args.get('author_name')
if author_name is None:
return render_template('visualizations/articles_by_author.html', data = [])
try:
# Check if the author_name is a valid string
author_name = str(author_name)
except ValueError:
# Return an error message if the author_name is not a valid string
return jsonify({"error": "Invalid author name. Please provide a valid string."})
if author_name:
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match documents that are authored by the specified author
{"$match": {"author": author_name}},
# Stage 2: Project the results to include necessary fields (e.g., title)
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"title": 1 # Include the title of the article
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Pass the result to the template
return render_template('visualizations/articles_by_author.html', data=result)
# 10. Route for getting articles by class
@app.route('/top_classes', methods=['GET'])
def top_classes():
"""
This route handles a GET request to '/top_classes'. It runs an aggregation pipeline on the 'articles' collection
to find and return the top 10 most frequent classes in the articles.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Unwind the 'classes' array, creating a document for each class
{"$unwind": "$classes"},
# Stage 2: Match only documents where the 'mapping' field is 'category'
{
"$match": {
"classes.mapping": "category"
}
},
# Stage 3: Group by the 'classes.value' (category) field and count the number of articles in each category
{
"$group": {
"_id": "$classes.value", # Group by the category value
"count": {"$sum": 1} # Count the number of articles for each category
}
},
# Stage 4: Sort by 'count' in descending order to get the most frequent classes
{
"$sort": {"count": -1} # Sort by count in descending order
},
# Stage 5: Limit the result to the top 10 classes
{
"$limit": 10
},
# Stage 6: Project the results, renaming '_id' to 'category' and keeping the 'count'
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"category": "$_id", # Rename '_id' to 'category'
"count": 1 # Include the 'count' field
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/top_classes.html', data=result)
# 11. Route for getting article details by postid
@app.route('/article_details', methods=['GET'])
def article_details():
"""
This route handles a GET request to '/article_details/<postid>'. It returns detailed information of a specific article
based on its postid.
"""
postid = request.args.get('postid')
if postid is None:
return render_template('visualizations/article_details.html', data = [])
if postid:
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match the document with the specified postId
{
"$match": {
"postId": postid # Replace 'postId' with the actual value passed to the route
}
},
# Stage 2
{
"$project": {
"_id": 0,
"title": 1,
"url": 1,
"keywords": 1,
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Pass the result to the template
return render_template('visualizations/article_details.html', data=result)
# 12. Route for getting articles with video
@app.route('/articles_with_video', methods=['GET'])
def articles_with_video():
"""
This route handles a GET request to '/articles_with_video'. It runs an aggregation pipeline on the 'articles' collection
to find and return all articles that contain a video (where video_duration is not null).
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match documents where 'video_duration' is not null
{"$match": {"video_duration": {"$ne": None}}},
# Stage 2: Project the results to include necessary fields (e.g., title)
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"title": 1, # Include the title of the article
"url": 1 # Include the URL of the article
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/articles_with_video.html', data=result)
# 13. Route for getting articles by year
@app.route('/articles_by_year', methods=['GET'])
def articles_by_year():
"""
This route handles a GET request to '/articles_by_year/<year>'. It runs an aggregation pipeline on the 'articles' collection
to return the number of articles published in the specified year.
"""
year = request.args.get('year')
if year is None:
return render_template('visualizations/articles_by_year.html', data = [])
try:
# Check if the year is a valid integer
year = int(year)
except ValueError:
# Return an error message if the year is not a valid integer
return jsonify({"error": "Invalid year. Please provide a valid integer."})
if year:
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match documents published in the specified year
{"$match": {
"published_time": {
"$gte": f"{year}-01-01T00:00:00Z",
"$lt": f"{year}-12-31T23:59:59Z"
}
}},
# Stage 2: Count the number of documents
{
"$count": "total_articles"
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/articles_by_year.html', data=result)
# 14. Route for getting the longest articles
@app.route('/longest_articles', methods=['GET'])
def longest_articles():
"""
This route handles a GET request to '/longest_articles'. It runs an aggregation pipeline on the 'articles' collection
to find and return the top 10 articles with the highest word count.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Convert 'word_count' from string to integer for accurate sorting
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"title": 1, # Include the title of the article
"word_count": {"$toInt": "$word_count"} # Convert 'word_count' to integer
}
},
# Stage 2: Sort the articles by 'word_count' in descending order
{"$sort": {"word_count": -1}},
# Stage 3: Limit the result to the top 10 articles
{"$limit": 10},
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/longest_articles.html', data=result)
# 15. Route for getting the shortest articles
@app.route('/shortest_articles', methods=['GET'])
def shortest_articles():
"""
This route handles a GET request to '/shortest_articles'. It runs an aggregation pipeline on the 'articles' collection
to find and return the top 10 articles with the lowest word count.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Convert 'word_count' from string to integer for accurate sorting
{
"$project": {
"_id": 0, # Exclude the original '_id' field
"title": 1, # Include the title of the article
"word_count": {"$toInt": "$word_count"} # Convert 'word_count' to integer
}
},
# Stage 2: Sort the articles by 'word_count' in increasing order
{"$sort": {"word_count": 1}},
# Stage 3: Limit the result to the top 10 articles
{"$limit": 10},
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/shortest_articles.html', data=result)
# 16. Route for getting articles by keyword count
@app.route('/articles_by_keyword_count', methods=['GET'])
def articles_by_keyword_count():
"""
This route handles a GET request to '/articles_by_keyword_count'. It runs an aggregation pipeline on the 'articles' collection
to return articles grouped by the number of keywords they contain.
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Calculate the number of keywords for each document
{
"$addFields": {
"keyword_count": {"$size": "$keywords"}
}
},
# Stage 2: Group by the 'keyword_count' and count the number of articles for each count
{
"$group": {
"_id": "$keyword_count",
"count": {"$sum": 1}
}
},
{
"$sort": {"count": 1, "keyword_count": 1}
},
# Stage 3: Project the results, renaming '_id' to 'keyword_count' and keeping the 'count'
{
"$project": {
"keyword_count": "$_id",
"count": 1,
"_id": 0
}
}
]
# Execute the aggregation pipeline on the collection
result = list(collection.aggregate(pipeline))
# Check if the request is for JSON or HTML
if request.args.get('format') == 'json':
# Return the result as a JSON response
return jsonify(result)
else:
# Render the result in an HTML template
return render_template('visualizations/articles_by_keyword_count.html', data=result)
# 17. Route for getting articles with thumbnail presence
@app.route('/articles_with_thumbnail', methods=['GET'])
def articles_with_thumbnail():
"""
This route handles a GET request to '/articles_with_thumbnail'. It runs an aggregation pipeline on the 'articles' collection
to find and return all articles that have a thumbnail image (where thumbnail is not null).
"""
# Define the aggregation pipeline
pipeline = [
# Stage 1: Match documents where 'thumbnail' is not null
{"$match": {"thumbnail": {"$ne": None}}},
# Stage 2: Project the results to include necessary fields (e.g., title, thumbnail, etc.)
{
"$project": {
"_id": 0, # Exclude the _id field
"title": 1, # Include the title of the article
"thumbnail": 1, # Include the thumbnail field
"url": 1, # Include the URL of the article (if needed)
"author": 1, # Include the author of the article (if needed)
"published_time": 1 # Include the published time of the article (if needed)
}