-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1821 lines (1404 loc) · 75 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
import datetime
import googleapiclient.discovery
import pandas as pd
import psycopg2
import pymongo
import plotly.express as px
import streamlit as st
from streamlit_option_menu import option_menu
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
def streamlit_config():
# page configuration
st.set_page_config(page_title='YouTube Data Harvesting and Warehousing',
page_icon=':bar_chart:', layout="wide")
# page header transparent color
page_background_color = """
<style>
[data-testid="stHeader"]
{
background: rgba(0,0,0,0);
}
</style>
"""
st.markdown(page_background_color, unsafe_allow_html=True)
# title and position
st.markdown(f'<h1 style="text-align: center;">YouTube Data Harvesting and Warehousing</h1>',
unsafe_allow_html=True)
class youtube_extract:
def channel(youtube, channel_id):
request = youtube.channels().list(
part='contentDetails, snippet, statistics, status',
id=channel_id)
response = request.execute()
data = {'channel_name': response['items'][0]['snippet']['title'],
'channel_id': response['items'][0]['id'],
'subscription_count': response['items'][0]['statistics']['subscriberCount'],
'channel_views': response['items'][0]['statistics']['viewCount'],
'channel_description': response['items'][0]['snippet']['description'],
'upload_id': response['items'][0]['contentDetails']['relatedPlaylists']['uploads'],
'country': response['items'][0]['snippet'].get('country', 'Not Available')}
return data
def playlist(youtube, channel_id, upload_id):
request = youtube.playlists().list(
part="snippet,contentDetails,status",
channelId=channel_id,
maxResults=50)
response = request.execute()
playlist = []
for i in range(0, len(response['items'])):
data = {'playlist_id': response['items'][i]['id'],
'playlist_name': response['items'][i]['snippet']['title'],
'channel_id': channel_id,
'upload_id': upload_id}
playlist.append(data)
next_page_token = response.get('nextPageToken')
# manually set umbrella = True for breaking while condition
umbrella = True
while umbrella:
if next_page_token is None:
umbrella = False
else:
request = youtube.playlists().list(
part="snippet,contentDetails,status",
channelId=channel_id,
maxResults=50,
pageToken=next_page_token)
response = request.execute()
for i in range(0, len(response['items'])):
data = {'playlist_id': response['items'][i]['id'],
'playlist_name': response['items'][i]['snippet']['title'],
'channel_id': channel_id,
'upload_id': upload_id}
playlist.append(data)
next_page_token = response.get('nextPageToken')
return playlist
def video_ids(youtube, upload_id):
request = youtube.playlistItems().list(
part='contentDetails',
playlistId=upload_id,
maxResults=50)
response = request.execute()
video_ids = []
for i in range(0, len(response['items'])):
data = response['items'][i]['contentDetails']['videoId']
video_ids.append(data)
next_page_token = response.get('nextPageToken')
# manually set umbrella = True for breaking while condition
umbrella = True
while umbrella:
if next_page_token is None:
umbrella = False
else:
request = youtube.playlistItems().list(
part='contentDetails',
playlistId=upload_id,
maxResults=50,
pageToken=next_page_token)
response = request.execute()
for i in range(0, len(response['items'])):
data = response['items'][i]['contentDetails']['videoId']
video_ids.append(data)
next_page_token = response.get('nextPageToken')
return video_ids
def video(youtube, video_id, upload_id):
request = youtube.videos().list(
part='contentDetails, snippet, statistics',
id=video_id)
response = request.execute()
caption = {'true': 'Available', 'false': 'Not Available'}
# convert PT15M33S to 00:15:33 format using Timedelta function in pandas
def time_duration(t):
a = pd.Timedelta(t)
b = str(a).split()[-1]
return b
data = {'video_id': response['items'][0]['id'],
'video_name': response['items'][0]['snippet']['title'],
'video_description': response['items'][0]['snippet']['description'],
'upload_id': upload_id,
'tags': response['items'][0]['snippet'].get('tags', []),
'published_date': response['items'][0]['snippet']['publishedAt'][0:10],
'published_time': response['items'][0]['snippet']['publishedAt'][11:19],
'view_count': response['items'][0]['statistics']['viewCount'],
'like_count': response['items'][0]['statistics'].get('likeCount', 0),
'favourite_count': response['items'][0]['statistics']['favoriteCount'],
'comment_count': response['items'][0]['statistics'].get('commentCount', 0),
'duration': time_duration(response['items'][0]['contentDetails']['duration']),
'thumbnail': response['items'][0]['snippet']['thumbnails']['default']['url'],
'caption_status': caption[response['items'][0]['contentDetails']['caption']]}
if data['tags'] == []:
del data['tags']
return data
def comment(youtube, video_id):
request = youtube.commentThreads().list(
part='id, snippet',
videoId=video_id,
maxResults=100)
response = request.execute()
comment = []
for i in range(0, len(response['items'])):
data = {'comment_id': response['items'][i]['id'],
'comment_text': response['items'][i]['snippet']['topLevelComment']['snippet']['textDisplay'],
'comment_author': response['items'][i]['snippet']['topLevelComment']['snippet']['authorDisplayName'],
'comment_published_date': response['items'][i]['snippet']['topLevelComment']['snippet']['publishedAt'][0:10],
'comment_published_time': response['items'][i]['snippet']['topLevelComment']['snippet']['publishedAt'][11:19],
'video_id': video_id}
comment.append(data)
return data
def main(channel_id):
channel = youtube_extract.channel(youtube, channel_id)
upload_id = channel['upload_id']
playlist = youtube_extract.playlist(youtube, channel_id, upload_id)
video_ids = youtube_extract.video_ids(youtube, upload_id)
video = []
comment = []
for i in video_ids:
v = youtube_extract.video(youtube, i, upload_id)
video.append(v)
# skip disabled comments error in looping function
try:
c = youtube_extract.comment(youtube, i)
comment.append(c)
except:
pass
final = {'channel': channel,
'playlist': playlist,
'video': video,
'comment': comment}
return final
def display_sample_data(channel_id):
channel = youtube_extract.channel(youtube, channel_id)
upload_id = channel['upload_id']
playlist = youtube_extract.playlist(youtube, channel_id, upload_id)
video_ids = youtube_extract.video_ids(youtube, upload_id)
video = []
comment = []
for i in video_ids:
v = youtube_extract.video(youtube, i, upload_id)
video.append(v)
# skip disabled comments error in looping function
try:
c = youtube_extract.comment(youtube, i)
comment.append(c)
except:
pass
break
final = {'channel': channel,
'playlist': playlist,
'video': video,
'comment': comment}
return final
class mongodb:
def data_storage(channel_name, database, data):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
col = db[channel_name]
col.insert_one(data)
def list_collection_names(database):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
col = db.list_collection_names()
col.sort(reverse=False)
return col
def order_collection_names(database):
m = mongodb.list_collection_names(database)
if m == []:
st.info("The Mongodb database is currently empty")
else:
st.subheader('List of collections in MongoDB database')
m = mongodb.list_collection_names(database)
c = 1
for i in m:
st.write(str(c) + ' - ' + i)
c += 1
def drop_temp_collection():
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi['temp']
col = db.list_collection_names()
if len(col) > 0:
for i in col:
db.drop_collection(i)
def main(database):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi['temp']
col = db.list_collection_names()
if len(col) == 0:
st.info("There is no data retrived from youtube")
else:
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi['temp']
col = db.list_collection_names()
channel_name = col[0]
# Now we get the channel name and access channel data
data_youtube = {}
col1 = db[channel_name]
for i in col1.find():
data_youtube.update(i)
# verify channel name already exists in database
list_collection_names = mongodb.list_collection_names(database)
if channel_name not in list_collection_names:
mongodb.data_storage(channel_name, database, data_youtube)
st.success(
"The data has been successfully stored in the MongoDB database")
st.balloons()
mongodb.drop_temp_collection()
else:
st.warning(
"The data has already been stored in MongoDB database")
option = st.radio('Do you want to overwrite the data currently stored?',
['Select one below', 'Yes', 'No'])
if option == 'Yes':
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
# delete existing data
db[channel_name].drop()
# add new data
mongodb.data_storage(channel_name, database, data_youtube)
st.success(
"The data has been successfully overwritten and updated in MongoDB database")
st.balloons()
mongodb.drop_temp_collection()
elif option == 'No':
mongodb.drop_temp_collection()
st.info("The data overwrite process has been skipped")
class sql:
def create_tables():
gopi = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi.cursor()
cursor.execute(f"""create table if not exists channel(
channel_id varchar(255) primary key,
channel_name varchar(255),
subscription_count int,
channel_views int,
channel_description text,
upload_id varchar(255),
country varchar(255));""")
cursor.execute(f"""create table if not exists playlist(
playlist_id varchar(255) primary key,
playlist_name varchar(255),
channel_id varchar(255),
upload_id varchar(255));""")
cursor.execute(f"""create table if not exists video(
video_id varchar(255) primary key,
video_name varchar(255),
video_description text,
upload_id varchar(255),
tags text,
published_date date,
published_time time,
view_count int,
like_count int,
favourite_count int,
comment_count int,
duration time,
thumbnail varchar(255),
caption_status varchar(255));""")
cursor.execute(f"""create table if not exists comment(
comment_id varchar(255) primary key,
comment_text text,
comment_author varchar(255),
comment_published_date date,
comment_published_time time,
video_id varchar(255));""")
gopi.commit()
def list_channel_names():
gopi = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi.cursor()
cursor.execute("select channel_name from channel")
s = cursor.fetchall()
s = [i[0] for i in s]
s.sort(reverse=False)
return s
def order_channel_names():
s = sql.list_channel_names()
if s == []:
st.info("The SQL database is currently empty")
else:
st.subheader("List of channels in SQL database")
c = 1
for i in s:
st.write(str(c) + ' - ' + i)
c += 1
def channel(database, channel_name):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
col = db[channel_name]
data = []
for i in col.find({}, {'_id': 0, 'channel': 1}):
data.append(i['channel'])
df = pd.DataFrame(data)
df = df.reindex(columns=['channel_id', 'channel_name', 'subscription_count', 'channel_views',
'channel_description', 'upload_id', 'country'])
df['subscription_count'] = pd.to_numeric(df['subscription_count'])
df['channel_views'] = pd.to_numeric(df['channel_views'])
return df
def playlist(database, channel_name):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
col = db[channel_name]
data = []
for i in col.find({}, {'_id': 0, 'playlist': 1}):
data.extend(i['playlist'])
df = pd.DataFrame(data)
df = df.reindex(
columns=['playlist_id', 'playlist_name', 'channel_id', 'upload_id'])
return df
def video(database, channel_name):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
col = db[channel_name]
data = []
for i in col.find({}, {'_id': 0, 'video': 1}):
data.extend(i['video'])
df = pd.DataFrame(data)
df = df.reindex(columns=['video_id', 'video_name', 'video_description', 'upload_id',
'tags', 'published_date', 'published_time', 'view_count',
'like_count', 'favourite_count', 'comment_count', 'duration',
'thumbnail', 'caption_status'])
df['published_date'] = pd.to_datetime(df['published_date']).dt.date
df['published_time'] = pd.to_datetime(
df['published_time'], format='%H:%M:%S').dt.time
df['view_count'] = pd.to_numeric(df['view_count'])
df['like_count'] = pd.to_numeric(df['like_count'])
df['favourite_count'] = pd.to_numeric(df['favourite_count'])
df['comment_count'] = pd.to_numeric(df['comment_count'])
df['duration'] = pd.to_datetime(
df['duration'], format='%H:%M:%S').dt.time
return df
def comment(database, channel_name):
gopi = pymongo.MongoClient(
"mongodb://gopiashokan:[email protected]:27017,ac-0vdscni-shard-00-01.xdp3lkp.mongodb.net:27017,ac-0vdscni-shard-00-02.xdp3lkp.mongodb.net:27017/?ssl=true&replicaSet=atlas-11e4qv-shard-0&authSource=admin&retryWrites=true&w=majority")
db = gopi[database]
col = db[channel_name]
data = []
for i in col.find({}, {'_id': 0, 'comment': 1}):
data.extend(i['comment'][0])
df = pd.DataFrame(data)
df = df.reindex(columns=['comment_id', 'comment_text', 'comment_author',
'comment_published_date', 'comment_published_time', 'video_id'])
df['comment_published_date'] = pd.to_datetime(
df['comment_published_date']).dt.date
df['comment_published_time'] = pd.to_datetime(
df['comment_published_time'], format='%H:%M:%S').dt.time
return df
def main(mdb_database, sql_database):
# create table in sql
sql.create_tables()
# mongodb and sql channel names
m = mongodb.list_collection_names(mdb_database)
s = sql.list_channel_names()
if s == m == []:
st.info("Both Mongodb and SQL databases are currently empty")
else:
# mongodb and sql channel names
mongodb.order_collection_names(mdb_database)
sql.order_channel_names()
# remaining channel name for migration
list_mongodb_notin_sql = ['Select one']
m = mongodb.list_collection_names(mdb_database)
s = sql.list_channel_names()
# verify channel name not in sql
for i in m:
if i not in s:
list_mongodb_notin_sql.append(i)
# channel name for user selection
option = st.selectbox('', list_mongodb_notin_sql)
if option == 'Select one':
col1, col2 = st.columns(2)
with col1:
st.warning('Please select the channel')
else:
channel = sql.channel(sql_database, option)
playlist = sql.playlist(sql_database, option)
video = sql.video(sql_database, option)
comment = sql.comment(sql_database, option)
gopi = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi.cursor()
cursor.executemany(f"""insert into channel(channel_id, channel_name, subscription_count,
channel_views, channel_description, upload_id, country)
values(%s,%s,%s,%s,%s,%s,%s)""", channel.values.tolist())
cursor.executemany(f"""insert into playlist(playlist_id, playlist_name, channel_id,
upload_id)
values(%s,%s,%s,%s)""", playlist.values.tolist())
cursor.executemany(f"""insert into video(video_id, video_name, video_description,
upload_id, tags, published_date, published_time, view_count,
like_count, favourite_count, comment_count, duration, thumbnail,
caption_status)
values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
video.values.tolist())
cursor.executemany(f"""insert into comment(comment_id, comment_text, comment_author,
comment_published_date, comment_published_time, video_id)
values(%s,%s,%s,%s,%s,%s)""", comment.values.tolist())
gopi.commit()
st.success("Migrated Data Successfully to SQL Data Warehouse")
st.balloons()
gopi.close()
class sql_queries:
def q1_allvideoname_channelname():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
# using Inner Join to join the tables
cursor.execute(f'''select video.video_name, channel.channel_name
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
group by video.video_id, channel.channel_id
order by channel.channel_name ASC''')
s = cursor.fetchall()
# add index for dataframe and set a column names
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Video Names', 'Channel Names'], index=i)
# add name for 'S.No'
data = data.rename_axis('S.No')
# index in center position of dataframe
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q2_channelname_totalvideos():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select distinct channel.channel_name, count(distinct video.video_id) as total
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
group by channel.channel_id
order by total DESC''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Channel Names', 'Total Videos'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q3_mostviewvideos_channelname():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select distinct video.video_name, video.view_count, channel.channel_name
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
order by video.view_count DESC
limit 10''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Video Names', 'Total Views', 'Channel Names'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q4_videonames_totalcomments():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select video.video_name, video.comment_count, channel.channel_name
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
group by video.video_id, channel.channel_name
order by video.comment_count DESC''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Video Names', 'Total Comments', 'Channel Names'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q5_videonames_highestlikes_channelname():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select distinct video.video_name, channel.channel_name, video.like_count
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
where video.like_count = (select max(like_count) from video)''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Video Names', 'Channel Names', 'Most Likes'], index=i)
data = data.reindex(columns=['Video Names', 'Most Likes', 'Channel Names'])
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q6_videonames_totallikes_channelname():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select distinct video.video_name, video.like_count, channel.channel_name
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
group by video.video_id, channel.channel_id
order by video.like_count DESC''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Video Names', 'Total Likes', 'Channel Names'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q7_channelnames_totalviews():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select channel_name, channel_views from channel
order by channel_views DESC''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Channel Names', 'Total Views'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q8_channelnames_releasevideos(year):
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f"""select distinct channel.channel_name, count(distinct video.video_id) as total
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
where extract(year from video.published_date) = '{year}'
group by channel.channel_id
order by total DESC""")
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Channel Names', 'Published Videos'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q9_channelnames_avgvideoduration():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select channel.channel_name, substring(cast(avg(video.duration) as varchar), 1, 8) as average
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
group by channel.channel_id
order by average DESC''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Channel Names', 'Average Video Duration'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def q10_videonames_channelnames_mostcomments():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f'''select video.video_name, video.comment_count, channel.channel_name
from video
inner join playlist on playlist.upload_id = video.upload_id
inner join channel on channel.channel_id = playlist.channel_id
group by video.video_id, channel.channel_name
order by video.comment_count DESC
limit 1''')
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
data = pd.DataFrame(s, columns=['Video Names', 'Channel Names', 'Total Comments'], index=i)
data = data.rename_axis('S.No')
data.index = data.index.map(lambda x: '{:^{}}'.format(x, 10))
return data
def main():
st.subheader('Select the Query below')
q1 = 'Q1-What are the names of all the videos and their corresponding channels?'
q2 = 'Q2-Which channels have the most number of videos, and how many videos do they have?'
q3 = 'Q3-What are the top 10 most viewed videos and their respective channels?'
q4 = 'Q4-How many comments were made on each video with their corresponding video names?'
q5 = 'Q5-Which videos have the highest number of likes with their corresponding channel names?'
q6 = 'Q6-What is the total number of likes for each video with their corresponding video names?'
q7 = 'Q7-What is the total number of views for each channel with their corresponding channel names?'
q8 = 'Q8-What are the names of all the channels that have published videos in the particular year?'
q9 = 'Q9-What is the average duration of all videos in each channel with corresponding channel names?'
q10 = 'Q10-Which videos have the highest number of comments with their corresponding channel names?'
query_option = st.selectbox(
'', ['Select One', q1, q2, q3, q4, q5, q6, q7, q8, q9, q10])
if query_option == q1:
st.dataframe(sql_queries.q1_allvideoname_channelname())
elif query_option == q2:
st.dataframe(sql_queries.q2_channelname_totalvideos())
elif query_option == q3:
st.dataframe(sql_queries.q3_mostviewvideos_channelname())
elif query_option == q4:
st.dataframe(sql_queries.q4_videonames_totalcomments())
elif query_option == q5:
st.dataframe(sql_queries.q5_videonames_highestlikes_channelname())
elif query_option == q6:
st.dataframe(sql_queries.q6_videonames_totallikes_channelname())
elif query_option == q7:
st.dataframe(sql_queries.q7_channelnames_totalviews())
elif query_option == q8:
year = st.text_input('Enter the year')
submit = st.button('Submit')
if submit:
st.dataframe(sql_queries.q8_channelnames_releasevideos(year))
elif query_option == q9:
st.dataframe(sql_queries.q9_channelnames_avgvideoduration())
elif query_option == q10:
st.dataframe(
sql_queries.q10_videonames_channelnames_mostcomments())
class channel_analysis:
def total_channel_names():
st.subheader('List of Channels')
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(
"select channel_name from channel order by channel_name ASC")
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
df = pd.DataFrame(s, columns=['Channel Names'], index=i)
df = df.rename_axis('S.No')
df.index = df.index.map(lambda x: '{:^{}}'.format(x, 10))
return df
def total_playlist_names():
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f"""select distinct playlist.playlist_name, channel.channel_name
from playlist
inner join channel on playlist.channel_id = channel.channel_id
group by playlist.playlist_name, channel.channel_name
order by channel.channel_name, playlist.playlist_name ASC""")
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
df = pd.DataFrame(
s, columns=['Playlist Names', 'Channel Names'], index=i)
df = df.reindex(columns=['Channel Names', 'Playlist Names'])
df = df.rename_axis('S.No')
df.index = df.index.map(lambda x: '{:^{}}'.format(x, 10))
return df
def total_playlist_names_select_channel(channel_name):
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f"""select distinct playlist.playlist_name, channel.channel_name
from playlist
inner join channel on playlist.channel_id = channel.channel_id
where channel.channel_name='{channel_name}'
group by playlist.playlist_id, channel.channel_name
order by channel.channel_name, playlist.playlist_name ASC""")
s = cursor.fetchall()
i = [i for i in range(1, len(s) + 1)]
df = pd.DataFrame(
s, columns=['Playlist Names', 'Channel Names'], index=i)
df = df.reindex(columns=['Channel Names', 'Playlist Names'])
df = df.rename_axis('S.No')
df.index = df.index.map(lambda x: '{:^{}}'.format(x, 10))
return df
def total_playlist_count():
st.subheader('Channel wise Playlists')
gopi_s = psycopg2.connect(host='localhost',
user='postgres',
password='root',
database='youtube')
cursor = gopi_s.cursor()
cursor.execute(f"""select distinct channel.channel_name, count(distinct playlist.playlist_id) as total