-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
3394 lines (2942 loc) · 159 KB
/
main.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
"""
Caption analytics
Usage:
main.py <host> <port> <debug>
main.py -h | --help
main.py --version
<host>:
<port>:
<debug>: DEBUG to keep the incoming data
Examples:
main.py 0.0.0.0 443
Options:
-h --help Show this screen.
--version Show version.
"""
import datetime
import sqlite3
import numpy as np
from docopt import docopt
from flask import Flask, request, jsonify,json
from flask import session as flask_session
from flask import redirect as flask_redirect
from flask import url_for as flask_url_for
from flask_cors import CORS
from flask import render_template
from flask import make_response
import requests
import pandas as pd
from vocab_suggest import vocab_calculate_all
from vocab_suggest import get_stats_for_levels_db
from vocab_suggest import vocab_result_save
from vocab_suggest import vocab_result_load
from vocab_suggest import get_frequently_used_words
from vocab_suggest import suggest_words
from vocab_suggest import extract_words_from_response
from vocab_suggest import remove_stopwords_entry
from vocab_suggest import grammatical_error_all
from vocab_suggest import grammatical_error_df
from save_to_storage import get_caption_html
from save_to_storage import get_delta
from save_to_storage import get_blending_logs
from strip_words import personalize_for_session_vocab
from strip_words import personalize_for_session_settings
from strip_words import personalize_for_session_authorization
from strip_words import grant_token_for_session
from strip_words import personalize_session_accept_authorization
from strip_words import personalize_calling_function
from strip_words import show_text_from_url
from session_model import list_session
from session_model import mask_email_address
from session_model import allowed_function_list
from session_model import build_calling_function
from json import JSONDecodeError
import config_settings
from google.oauth2.credentials import Credentials
import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery
from google.auth.exceptions import RefreshError
import os
DB_NAME = "main.db"
DB_NAME_SITE = "site.db"
DB_NAME_LOG = "log.db"
DB_NAME_AUTH = "session_auth.db"
REL_SESSION_GRANTED_ID = "grant_authorized"
app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
CORS(app)
# This variable specifies the name of a file that contains the OAuth 2.0
# information for this application, including its client_id and client_secret.
CLIENT_SECRETS_FILE, config_messsage_text = config_settings.get_value(['oauth','CLIENT_SECRETS_FILE'])
# Note: A secret key is included in the sample so that it works.
# If you use this code in your application, replace this with a truly secret
# key. See https://flask.palletsprojects.com/quickstart/#sessions.
app.secret_key,config_messsage_text = config_settings.get_value(['oauth','SECRET_KEY'])
# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/userinfo.email','openid','https://www.googleapis.com/auth/userinfo.profile']
API_SERVICE_NAME = 'oauth2'
API_VERSION = 'v2'
loaded_vocab_ngsl = pd.read_csv("NGSL+1.txt", delimiter="\t")
dict_ngsl_level = {row['Lemma']: index for index, row in loaded_vocab_ngsl.iterrows()}
def is_correct_session_access_code(session_string="", option_settings=""):
# - ip and username will not work due to users not sending any data to server
# 1: with json access_key
# read session_access_code and grant action if correct
return True, None
@app.route('/prompt_check',methods=['POST','GET'])
def return_prompt_options():
data_received = request.get_data().decode('utf-8')
data_json = json.loads(data_received)
username = data_json['username']
session_string = data_json['transcriptId']
print("username:",username)
option_settings = data_json['option_settings']
config_server_security_granted, message_json = config_settings.get_full_access_settings()
if config_server_security_granted is None:
# use error text
return message_json
elif config_server_security_granted != True:
# true: fullaccess granted
is_granted, message_json = is_correct_session_access_code(session_string=session_string, option_settings=option_settings)
if is_granted != True:
return message_json
google_access_token = data_json['google_access_token']
userinfo_id = None
useremail = None
session_id = None
# check every n min.
if (google_access_token == ""):
if ('credentials' in flask_session):
if ('token' in flask_session['credentials']):
google_access_token = flask_session['credentials']['token']
else:
data = [{'not_authenticated': True}]
return jsonify(data)
if (google_access_token != ""):
userinfo_id, useremail = get_authentication_session_settings(username="",
authorization_token=google_access_token)
session_id = get_sessionid(session_string=session_string,owner=userinfo_id,create_if_not_exists=True)
if session_id is None or session_id == "":
data = [{'not_authenticated': True}]
return jsonify(data)
session_string = session_id
df_session_vocab_to_cover, df_session_vocab_to_suggest, df_session_vocab_to_avoid = \
get_session_settings(username=username,session_string=session_string)
df_session_vocab_to_cover_all, df_session_vocab_to_suggest_all, df_session_vocab_to_avoid_all = \
get_session_settings(username="all",session_string=session_string)
dbname = DB_NAME
conn = sqlite3.connect(dbname)
df_session_caption = pd.read_sql("SELECT * FROM caption where " + \
" session = '" + session_string + "'"
, conn)
df_session_prompt = pd.read_sql("SELECT * FROM session_prompt_log where " + \
" session = '" + session_string + "'"
, conn)
conn.commit()
conn.close()
df_vocab_avoid = None
if df_session_vocab_to_avoid is not None:
df_vocab_avoid = pd.merge(df_session_vocab_to_avoid.reset_index(), pd.concat(
[pd.DataFrame(df_session_vocab_to_avoid.index, columns=['index']),
pd.DataFrame(list(df_session_vocab_to_avoid['value'].str.split(":")))], axis=1))
# pd.concat([df_session_vocab_to_avoid.reset_index(), pd.concat(
# [pd.DataFrame(df_session_vocab_to_avoid.index, columns=['index']),
# pd.DataFrame(list(df_session_vocab_to_avoid['value'].str.split(":")))], axis=1)], axis=1)
# pd.concat([ pd.DataFrame(list(df_session_vocab_to_avoid['value'].str.split(":")))])
if df_session_vocab_to_avoid_all is not None:
df_vocab_avoid_all = pd.merge(df_session_vocab_to_avoid_all.reset_index(), pd.concat(
[pd.DataFrame(df_session_vocab_to_avoid_all.index, columns=['index']),
pd.DataFrame(list(df_session_vocab_to_avoid_all['value'].str.split(":")))], axis=1))
# df_vocab_avoid = pd.DataFrame(list(df_session_vocab_to_avoid_all['value'].str.split(":")))
df_vocab_avoid = pd.concat([df_vocab_avoid, df_vocab_avoid_all])
if df_vocab_avoid is not None and len(df_vocab_avoid) > 0:
df_vocab_avoid.columns=['index','session','actor','key','value','vocab','frequency','interval']
else:
df_vocab_avoid = pd.DataFrame()
if df_session_vocab_to_suggest_all is not None:
df_vocab_suggest = pd.DataFrame(list(df_session_vocab_to_suggest_all['value'].str.split(":")))
if df_vocab_suggest is not None and len(df_vocab_suggest) > 0:
df_vocab_suggest.columns=['vocab','frequency','interval']
# TODO: merge check all and specific user
for index, item in df_vocab_avoid.iterrows():
df_hit = df_session_caption['text'].str.contains(item['vocab'] ,case=False)
if len(df_hit) != 0:
import re
df_hit2 = df_session_caption[df_session_caption['text'].str.contains(item['vocab'], case=False)]['text'].apply(lambda s: len(re.findall(item['vocab'],s)))
df_hit_index = df_session_caption[df_session_caption['text'].str.contains(item['vocab'], case=False)]['text'].apply(lambda s: len(re.findall(item['vocab'],s)))
df_hit_re_index = df_session_caption['text'].apply(lambda s: len(re.findall(item['vocab'], s, flags=re.IGNORECASE)))
# actor should be ignored as filtered
df_hit_re_index = df_session_caption[df_session_caption['actor'] == item['actor']]['text'].apply(
lambda s: len(re.findall(item['vocab'], s, flags=re.IGNORECASE)))
df_hit_re_index = df_session_caption[df_session_caption['actor'] == username]['text'].apply(
lambda s: len(re.findall(item['vocab'], s, flags=re.IGNORECASE)))
if len(df_hit_re_index) == 0:
continue
max_end = df_session_caption[df_hit_re_index > 0]['end'].max()
print(df_hit2.sum())
num_of_occurance = df_hit_re_index.sum()
# counter (all, username)
# history of alert to avoid duplicate notice. Should be through history.
if item['frequency'] is not None and num_of_occurance >= int(item['frequency']):
if num_of_occurance == int(item['frequency']):
if len(df_session_prompt[
(df_session_prompt['key'] == 'vocab_to_avoid') & (df_session_prompt['value'] == item['vocab']) &
(df_session_prompt['actor'] == username) &
(df_session_prompt['triggering_criteria'] == str(num_of_occurance))]) == 0:
data_show = {"notification": {"text": "Avoid the specific word"},
"heading": f"You have used {item['vocab']} for {num_of_occurance} times.<br>",
"prompt_options": "Yes<br>,No<br>,Maybe",
"setting":
{"duration": 3000}
}
df_new = pd.DataFrame(columns=['session','start','actor','key','value','triggering_criteria'])
tmp_se = pd.Series({
'session': session_string,
'start': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'actor': username,
'key': 'vocab_to_avoid',
'value': item['vocab'],
'triggering_criteria': str(num_of_occurance)
}, index=df_new.columns)
df_new = df_new.append(tmp_se, ignore_index=True)
dbname = DB_NAME
conn = sqlite3.connect(dbname)
df_new.to_sql('session_prompt_log', conn, if_exists='append', index=False)
conn.commit()
conn.close()
return jsonify(data_show)
elif ( (num_of_occurance - (int(item['frequency']))) % int(item['interval'])) == 0:
if len(df_session_prompt[
(df_session_prompt['key'] == 'vocab_to_avoid') & (df_session_prompt['value'] == item['vocab']) &
(df_session_prompt['actor'] == username) &
(df_session_prompt['triggering_criteria'] == str(num_of_occurance))])== 0:
data_show = {"notification": {"text": "Avoid the specific word"},
"heading": f"You have used {item['vocab']} for {num_of_occurance} times.<br>",
"prompt_options": "Yes<br>,No<br>,Maybe",
"setting":
{"duration": 3000}
}
df_new = pd.DataFrame(columns=['session','start','actor','key','value','triggering_criteria'])
tmp_se = pd.Series({
'session': session_string,
'start': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'actor': username,
'key': 'vocab_to_avoid',
'value': item['vocab'],
'triggering_criteria': str(num_of_occurance)
}, index=df_new.columns)
df_new = df_new.append(tmp_se, ignore_index=True)
dbname = DB_NAME
conn = sqlite3.connect(dbname)
df_new.to_sql('session_prompt_log', conn, if_exists='append', index=False)
conn.commit()
conn.close()
return jsonify(data_show)
else:
print(f"no hit for {item['vocab']}")
# session_start = datetime.datetime(2020, 9, 10, 0, 0, 0)
# session_start_string = session_start.strftime("%Y-%m-%d %H:%M:%S.%f")
# if (0 <= (datetime.datetime.now().second % 15) <= 0):
#
# data_show = {"notification": {"text": "no data exists from Meet"},
# "heading": "Would you like to volunteer to answer the question? Choose an option from the prompt.<br>",
# "prompt_options": "Yes<br>,No<br>,Maybe",
# "setting":
# {"duration": 3000}
# }
# return jsonify(data_show)
# elif (7 <= (datetime.datetime.now().second % 10) <= 7):
#
# data_show = {"notification": {"text": "no data exists from Meet"},
# "heading": "'You know' is repetitively used. Avoid using the phrase.<br>",
# "prompt_options": "Ok,<br>Not necessary",
# "setting":
# {"duration": 3000}
# }
# return jsonify(data_show)
#
# else:
data_show = {"notification": {"text": "no data exists from Meet"},
"heading": "no data",
"prompt_options": "",
"setting":
{"duration": 10}
}
return jsonify(data_show)
@app.route('/caption',methods=['POST','GET'])
def return_caption():
received_second = request.args.get('seconds')
received_session = request.args.get('session')
received_ip_address = request.remote_addr
if 'credentials' not in flask_session:
return flask_redirect("authorize")
google_userid, google_part_of_email = get_user_id_from_session()
# session_id = get_sessionid(session_string=received_session,owner=google_userid)
session_access_allowed, external_session_name = is_allowed_to_access(session_id=received_session,access_user=google_userid)
if google_userid is None:
return flask_redirect("authorize")
if session_access_allowed == False:
text = get_caption_html(session=received_session, start=None)
return text
if received_second is None:
text = get_caption_html(session=received_session, start=None)
return text
if received_second == "0":
df = get_delta(session=received_session, start=None)
else:
start_time = datetime.datetime.now() - datetime.timedelta(seconds=10, minutes=0)
df = get_delta(session=received_session, start=start_time)
if len(df) == 0:
print("reread with an extended time")
start_time = datetime.datetime.now() - datetime.timedelta(seconds=0, minutes=2)
df = get_delta(session=received_session, start=start_time)
df = get_blending_logs(session=received_session,start=None,df_caption=df)
text = df.to_json(orient="records")
return text
@app.route('/log',methods=['POST','GET'])
def receive_log():
data = request.get_data().decode('utf-8')
# print("Log",data)
data_json = json.loads(data)
username = data_json['username']
print("username:",username)
if len(data_json['text']) == 0:
data = [{"name": "no data exists",
"duration": 0}]
return jsonify( data)
input_text = data_json['text']
logtype = data_json['logtype']
logtime = data_json['logtime']
date_string_iso = data_json['date']
# date_string = (datetime.datetime.fromisoformat(date_string_iso.split(".")[0]) + datetime.timedelta(hours=9)).strftime("%Y-%m-%d %H:%M:%S")
date_string = (datetime.datetime.fromisoformat(str(date_string_iso).replace("Z","")) + datetime.timedelta(hours=9)).strftime("%Y-%m-%d %H:%M:%S.%f")
if logtime is not None:
logtime_string = (datetime.datetime.fromisoformat(str(logtime).replace("Z","")) + datetime.timedelta(hours=9)).strftime("%Y-%m-%d %H:%M:%S.%f")
date_string = logtime_string
# session_id = data_json['transcriptId']
session_string = data_json['transcriptId']
google_access_token = data_json['google_access_token']
userinfo_id = None
useremail = None
session_id = None
# check every n min.
if (google_access_token == ""):
data = [{'not_authenticated': True}]
return jsonify(data)
if (google_access_token != ""):
userinfo_id, useremail = get_authentication_session_settings(username="",
authorization_token=google_access_token)
session_id = get_sessionid(session_string=session_string,owner=userinfo_id,create_if_not_exists=False)
if session_id is None or session_id == "":
data = [{'not_authenticated': True}]
return jsonify(data)
df_new = pd.DataFrame(
columns=['session', 'start', 'actor', 'text','logtype','actor_account' ])
tmp_se = pd.Series({
'session': session_id,
'start': date_string,
'actor': username,
'text': input_text,
'logtype': logtype,
'actor_account': userinfo_id,
}, index=df_new.columns)
df_new = df_new.append(tmp_se, ignore_index=True)
dbname = DB_NAME
conn = sqlite3.connect(dbname)
df_new.to_sql('log', conn, if_exists='append', index=False)
# conn.execute("INSERT INTO log ( session , start , actor , text, logtype ) values ( " + \
# "'" + session_id + "'," + \
# "'" + date_string + "'," +\
# "'" + username + "'," + \
# "'" + input_text + "'," +
# "'" + logtype + "'" + \
# " )")
conn.commit()
conn.close()
data = [{"name": "update",
"duration": 0}]
return jsonify(data)
return data
@app.route('/livecaption',methods=['POST','GET'])
def return_heartbeat():
data = request.get_data().decode('utf-8')
data_json = json.loads(data)
username = data_json['username']
user_ip_address = request.remote_addr
print(f"username:{username}(at {user_ip_address})")
if len(data_json['transcript']) == 0:
data = [{"name": "no data exists",
"duration": 0}]
return jsonify( data)
session_string = data_json['transcriptId']
google_access_token = data_json['google_access_token']
userinfo_id = None
useremail = None
session_id = None
# check every n min.
if (google_access_token == ""):
data = [{'not_authenticated': True}]
return jsonify(data)
if (google_access_token != ""):
userinfo_id, useremail = get_authentication_session_settings(username="",
authorization_token=google_access_token)
session_id = get_sessionid(session_string=session_string,owner=userinfo_id,create_if_not_exists=True)
if session_id is None or session_id == "":
data = [{'not_authenticated': True}]
return jsonify(data)
session_string = session_id
# print(data_json['transcript']) #disable for non latin participant names
df = pd.DataFrame(data_json['transcript'])
df.columns = ['dateStart','dateEnd',
'actor','text']
df['start'] = pd.to_datetime(df['dateStart'].str.replace("Z","")) + datetime.timedelta(hours=9)
df['end'] = pd.to_datetime(df['dateEnd'].str.replace("Z","")) + datetime.timedelta(hours=9)
df['dif'] = df['end'] - df['start']
df['session'] = session_string
df['actor_ip'] = user_ip_address
df['actor_account'] = userinfo_id
# if (datetime.datetime.now().second % 4 == 0):
# sequence = int(datetime.datetime.now().second / 4) + int(datetime.datetime.now().minute * 60 / 4) + \
# int(datetime.datetime.now().hour * 3600 / 4) + int(datetime.datetime.now().day * 86400 / 4)
# # sending_text = df['text'][-1:].to_string().encode('utf-8')
# sending_text = str(sequence).encode('utf-8') + \
# str.join("\n", [str.join(" ", df['text'][-1:].to_string().split(" ")[a:a + 8]) for a in
# range(0, len(df['text'][-1:].to_string().split(" ")), 8)]).encode('utf-8')
# url = "http://API call"
# url += f"&seq={sequence}&lang=en-US"
# import requests
# post_data_to_endpoint = sending_text
# return_object = requests.post(url, data=post_data_to_endpoint)
# print(f"endpoint response ({sending_text})",return_object.text,return_object.status_code)
#
# print("df in /",df)
# print(df.columns)
df.drop(['dateStart','dateEnd','dif'],axis=1, inplace=True)
# df.drop(['time','timeEnd','year','month','day','hour','min','sec',
# 'yearend', 'monthend', 'dayend', 'hourend', 'minend', 'secend','dif'
# ],axis=1,inplace=True)
# print(df.columns)
df.columns=['actor','text','start','end','session','actor_ip','actor_account']
if 'log_incoming_message' in globals():
if log_incoming_message == "DEBUG":
df_incoming = df.copy()
df_incoming.drop(['text','actor_ip'],axis=1, inplace=True)
df_incoming['received_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
df_incoming['json'] = data
insert_incoming_log(df=df_incoming)
# print("df in / after",df)
dbname = DB_NAME
conn = sqlite3.connect(dbname)
# df_existing = pd.read_sql("SELECT * FROM caption where session = '" + session_string + "'"
# " order by id limit 3", #older captions are not needed
# conn)
caption_start = df['start'].min()
caption_start_string = caption_start.strftime("%Y-%m-%d %H:%M:%S.%f")
df_existing = pd.read_sql("SELECT * FROM caption where session = '" + session_string + "'" + \
" and start >= '" + caption_start_string + "'"
, conn)
df_existing['start'] = pd.to_datetime(df_existing['start'],format="%Y-%m-%d %H:%M:%S.%f")
df_existing['end'] = pd.to_datetime(df_existing['end'],format="%Y-%m-%d %H:%M:%S.%f")
if len(df_existing) != 0:
caption_sub_start = df_existing['start'].min()
caption_sub_start_string = caption_sub_start.strftime("%Y-%m-%d %H:%M:%S.%f")
df_existing_sub = pd.read_sql("SELECT * FROM caption_sub where session = '" + session_string + "'" + \
" and start >= '" + caption_sub_start_string + "'"
, conn)
else:
df_existing_sub = pd.read_sql("SELECT * FROM caption_sub where session = '" + session_string + "'"
, conn)
df_existing_sub['start'] = pd.to_datetime(df_existing_sub['start'],format="%Y-%m-%d %H:%M:%S.%f")
df_existing_sub['end'] = pd.to_datetime(df_existing_sub['end'],format="%Y-%m-%d %H:%M:%S.%f")
conn.commit()
conn.close()
df, df_existing, df_existing_sub, df_existing_sub_new = \
record_captions(df = df,
df_existing = df_existing,
df_existing_sub = df_existing_sub)
update_captions_to_db(df = df,
df_existing = df_existing,
df_existing_sub = df_existing_sub,
df_existing_sub_new=df_existing_sub_new)
# read last vocab_aggregate
# find caption larger than max in vocab_aggregate, but not max of df
df_vocab = vocab_calculate_all(session_string=session_string, since_last_update = True, include_last_record=False)
#TODO: last record needs processing after the session close
vocab_result_save(df=df_vocab ,db_target_name="vocab_aggregate")
data = [{"name": "data received",
"duration": 0}]
return jsonify(data)
def record_captions(df:pd.DataFrame=None,df_existing:pd.DataFrame=None,df_existing_sub:pd.DataFrame=None):
columns_sub=['session','start','substart','end','actor','text']
df_existing_sub_new = pd.DataFrame(columns=columns_sub)
df_remove_list = []
df_existing_remove_list = []
for index, row in df.iterrows():
# to skip processing (no update needed)
df_to_remove_index = ((df_existing['start'] == row['start']) & (df_existing['end'] == row['end']) & \
(df_existing['actor'] == row['actor']) & (df_existing['session'] == row['session']) &
(df_existing['text'] == row['text']))
# df_to_remove_index = ((row['start'].isin(df_existing['start']))&(row['end'].isin(df_existing['end']))& \
# (row['actor'].isin(df_existing['actor']))&(row['session'].isin(df_existing['session']))&
# (row['text'].isin(df_existing['text'])))
if len(df_existing[df_to_remove_index]):
df_remove_list.append(index)
df_existing = df_existing[-df_to_remove_index]
df.drop(index=df_remove_list, inplace=True)
df_remove_list = []
df_update_list = []
# only the end time is updated
for index, row in df.iterrows():
# to skip processing (update of the time needed)
# TODO: should the caption_sub be updated
df_to_update_index = ((df_existing['start'] == row['start']) & (df_existing['end'] != row['end']) & \
(df_existing['actor'] == row['actor']) & (df_existing['session'] == row['session']) &
(df_existing['text'] == row['text']))
# df_to_remove_index = ((row['start'].isin(df_existing['start']))&(row['end'].isin(df_existing['end']))& \
# (row['actor'].isin(df_existing['actor']))&(row['session'].isin(df_existing['session']))&
# (row['text'].isin(df_existing['text'])))
if len(df_existing[df_to_update_index]) != 0:
# df_existing[df_to_update_index]['end'][0], df['end'][0], df_existing.iloc[1, :], df_to_update_index, \
# df_existing[df_to_update_index].index, df_existing.iloc[
try:
df_existing.iloc[df_existing[df_to_update_index].index, df_existing.columns.get_loc('end')] = pd.Series(
row['end'])
except IndexError as e:
print("DEBUG: index 3 is out of bounds for axis 0 with size 3")
# df_existing[df_to_update_index].index, df_existing.columns.get_loc('end')], pd.Series(row['end'])
df_update_list.append(index)
# update table entry and dataframe
# df_existing[df_to_update_index]
# replace pairs
maketrans_str = {'.': '',
',': '',
'?': '',
'!': '',
}
maketrans_pairs = str.maketrans(maketrans_str)
def front_loading_parts(row_words:list=[],existing_words:list=[]):
def word_n_gram(words, N):
result = []
for it, c in enumerate(words):
if it + N > len(words):
return result
result.append(words[it: it + N])
n_gram_row = word_n_gram(row_words, 3)
n_gram_exist = word_n_gram(existing_words, 3)
# if row or exist are not in sufficient length, use what?
front_load_part_string = ""
front_load_part = None
front_load_latter_part = None
if len(n_gram_row) == 0 or len(n_gram_exist) == 0:
print("shorter than length = 3")
if len(n_gram_row) == 0:
return front_load_part_string, front_load_part, front_load_latter_part
if n_gram_row[0] in n_gram_exist:
found_new_in_past = [i for i, x in enumerate(n_gram_exist) if x == n_gram_row[0]]
found_new_in_past = found_new_in_past[0]
# copy first i items to new
front_load_part = existing_words[:found_new_in_past]
front_load_latter_part = existing_words[found_new_in_past:]
row_words_to_front_load = row['text'].split(" ")
found_past_in_new = [[i, t, n_gram_row[i], n_gram_exist[t]] for i, x in enumerate(n_gram_row) for t in
range(0, len(n_gram_exist) - 1, 1) if x == n_gram_exist[t]]
start_position = 0
for exist_item in front_load_part:
try:
start_position += re.search(exist_item, existing_row['text'][start_position:],
flags=re.IGNORECASE).end()
front_load_part_string = existing_row['text'][:start_position]
except AttributeError as e:
print(e)
#TODO handle
return front_load_part_string, front_load_part, front_load_latter_part
def reconstruct_from_list(row_original_text = "", existing_words:list = [],):
delta_text = ""
for exist_item in existing_words:
re_compile = re.compile(exist_item, re.IGNORECASE | re.MULTILINE)
row_original_text_in = row_original_text
row_original_text = re_compile.sub("", row_original_text, 1)
if row_original_text_in != row_original_text:
# trailing space or characters must be removed.
if len(row_original_text) != 0 and row_original_text[0] in ['.', '?', ',']:
row_original_text = row_original_text[1:]
row_original_text = row_original_text.lstrip()
delta_text = row_original_text
delta_text = delta_text.lstrip()
return delta_text
if len(row['text'].split(" ")) >= 5:
print("now check")
for index, row in df.iterrows():
df_to_duplicate_index_sub = ((df_existing_sub['start'] == row['start'])& \
(df_existing_sub['actor'] == row['actor'])&(df_existing_sub['session'] == row['session']))
if (df_to_duplicate_index_sub.sum()) > 0:
df_original_lines_w_id = df_existing_sub[df_to_duplicate_index_sub]
df_original_lines_w_id.drop(['id'], axis=1, inplace=True)
df_dup_lines = df_original_lines_w_id[df_original_lines_w_id.duplicated()]
if len(df_dup_lines) > 3:
print("check here")
# to skip processing (no update needed)
df_to_compare_index = ((df_existing['start'] == row['start'])& \
(df_existing['actor'] == row['actor'])&(df_existing['session'] == row['session']))
if len(df_existing[df_to_compare_index]) == 0:
if row['start'] == row['end']:
print( row['start'], # substart
row['end'])
# the very first cap
row['end'] = row['end'] + datetime.timedelta(microseconds=10000)
tmp_se = pd.Series([
row['session'],
row['start'],
row['start'], # substart
row['end'],
row['actor'],
row['text']
], index=df_existing_sub_new.columns)
df_existing_sub_new = df_existing_sub_new.append(tmp_se, ignore_index=True)
continue
elif len(df_existing[df_to_compare_index]) >= 2:
print("more than one line")
is_found_in_the_pattern_1 = False
is_found_in_the_pattern_2 = False
import re
# find with new in old string
# 0) all parts match
# 1) first part in old match new => extend to the last part
# 2) first part is different => add existing parts to the current part
# 1) first part in old match new => extend to the last part
row_words = row['text'].translate(maketrans_pairs).replace(' ', ' ').upper().rstrip().split(" ")
for index_existing, existing_row in df_existing[df_to_compare_index].iterrows():
existing_words = existing_row['text'].translate(maketrans_pairs).replace(' ', ' ').upper().rstrip().split(" ")
# 0) all parts match
if (existing_words == row_words) == True:
is_found_in_the_pattern_1 = True
is_found_in_the_pattern_2 = True
df_remove_list.append(index) # no additional entry needed in df
df_existing_remove_list.append(index_existing) # no additional entry needed in df
break
# 1) first part in old match new => extend to the last part
# existing_words = existing_row['text'].translate(maketrans_pairs).replace(' ', ' ').upper().rstrip().split(" ")
# overwrite with new one + delta to be added to sub by deleting the old one and
# find last part of existing one and find additional text to add to a new caption_sub
delta_text = None
frontload_string, frontload_former_part, frontload_latter_part\
= front_loading_parts(row_words=row_words, existing_words=existing_words)
if (frontload_latter_part == row_words) == True:
# no need to add to sub
is_found_in_the_pattern_1 = True
is_found_in_the_pattern_2 = True
df_remove_list.append(index) # no additional entry needed in df
df_existing_remove_list.append(index_existing) # no additional entry needed in df
break
if (existing_words == row_words[:len(existing_words)]) == True:
# first word part match
delta_text = reconstruct_from_list(row['text'], existing_words)
if len(delta_text) > 50:
print("do sometihng")
# first two words have to match
if delta_text is None and (existing_words[1:2]==row_words[1:2]):
s_row = set(row_words)
s_exist = set(existing_words)
s_subset = s_exist.issubset(s_row)
if s_subset == True:
row_original_text = row['text']
for exist_item in existing_words:
re_compile = re.compile(exist_item + " ", re.IGNORECASE | re.MULTILINE)
# found_segments = re_compile.search(row['text'][0:40])
row_original_text = re_compile.sub("",row_original_text,1)
delta_text = row_original_text
delta_text = delta_text.lstrip()
if len(delta_text) > 50:
print("do sometihng")
else:
# tolerate smaller differences
#("You know. It's my day off. So, good job. Let's see. Mike, what's",
# "You know. It's my day off. So, good job. let's see, what ")
# (existing_row['text'])
# That's such a, that's such a bless. Because I have to. I have to reproduce the program. To see what is going in on. and this is only happened, when The. Text. Rolled up and the older text are hidden. Otherwise, it's not going to happen. That's only the chance. I have. When? It's closed. It's the only. Part of the, Part of the difference. I'm going to I'm sight.
# Because that's That's the <<thing that the thing>> supergor
# (existing)
# finding_word: '<<thing that the thing>> supergor'
# (new, incoming)
# clean_row_text: That's such a that's such a bless Because I have to I have to reproduce the program To see what is going in on and this is only happened when The Text Rolled up and the older text are hidden Otherwise it's not going to happen That's only the chance I have When It's closed It's the only Part of the Part of the difference I'm going to I'm sight
# Because that's that's the <<thing that the thing>>
s_difference = s_row.difference(s_exist)
magic_number = 3
if len(s_difference) < magic_number:
# TODO: no retroactive changes to past caption_sub
# TODO: always frontload texts that are not included in row['text']
#frontload_string, frontload_former_part, frontload_latter_part
if frontload_latter_part is None:
delta_text = reconstruct_from_list(row['text'], existing_words)
elif (frontload_latter_part) == 0:
delta_text = reconstruct_from_list(row['text'], existing_words)
else:
delta_text = reconstruct_from_list(row['text'], frontload_latter_part)
if len(delta_text) > 50:
print("do sometihng")
else:
print("do something")
# TODO: too much different
if delta_text is not None:
df_existing.at[index_existing, "text"] = row["text"]
df_remove_list.append(index) # no additional entry needed in df
df_existing_sub_reference = df_existing_sub[df_existing_sub['start'] == row['start']][-1:]
if row['start'] == df_existing_sub_reference['end'].values[0]:
print('stpo here')
if row['text'] != delta_text:
tmp_se = pd.Series([
row['session'],
row['start'],
df_existing_sub_reference['end'].values[0], #substart
row['end'],
row['actor'],
delta_text
], index=df_existing_sub_new.columns)
df_existing_sub_new = df_existing_sub_new.append(tmp_se, ignore_index=True)
is_found_in_the_pattern_1 = True
break
if is_found_in_the_pattern_1 == True:
continue
# 2) first part is different => add existing parts to the current part
# incoming text is longer -> can't find it in the past lines....
s_row = set(row_words)
# remove the ones that have been invalidated to avoid processing the invalided ones again
df_existing.drop(index=df_existing_remove_list, inplace=True)
df_existing_remove_list = []
for index_existing, existing_row in df_existing[df_to_compare_index].iterrows():
existing_words = existing_row['text'].translate(maketrans_pairs).replace(' ', ' ').upper().split(" ")
s_exist = set(existing_words)
s_difference = s_row - s_exist
s_common = s_row & s_exist
s_all = s_row | s_exist
s_sym = s_row ^ s_exist
print(s_difference)
print("s_dif", list(s_difference))
print("s_com", list(s_common))
print("s_all", list(s_all))
print("s_sym", list(s_sym))
print(len(list(s_difference)))
def word_n_gram(words, N):
result = []
for it, c in enumerate(words):
if it + N > len(words):
return result
result.append(words[it: it + N])
n_gram_row = word_n_gram(row_words, 3)
n_gram_exist = word_n_gram(existing_words, 3)
# if row or exist are not in sufficient length, use what?
if len(n_gram_row) == 0 or len(n_gram_exist) == 0:
print("shorter than length = 3")
continue # TODO: fewer words or contiuous string
# TODO: handle fewer words
# critically essential to handle for zoom due to the smaller size of letters sent to server.
if n_gram_row[0] in n_gram_exist:
found_new_in_past = [i for i, x in enumerate(n_gram_exist) if x == n_gram_row[0]]
found_new_in_past = found_new_in_past[0]
# copy first i items to new
front_load_part = existing_words[:found_new_in_past]
frontload_latter_part = existing_words[found_new_in_past:]
row_words_to_front_load = row['text'].split(" ")
found_past_in_new = [[i,t,n_gram_row[i],n_gram_exist[t]] for i, x in enumerate(n_gram_row) for t in range(0,len(n_gram_exist)-1,1) if x == n_gram_exist[t]]
start_position = 0
front_load_part_string = ""
for exist_item in front_load_part:
try:
start_position += re.search(exist_item, existing_row['text'][start_position:], flags=re.IGNORECASE).end()
front_load_part_string = existing_row['text'][:start_position]
except AttributeError as e:
print(e)
# TODO handle
except Exception as e:
print(e)
# TODO handle
row_original_text = row['text']
for exist_item in existing_words[found_new_in_past:]:
try:
re_compile = re.compile(exist_item + " ", re.IGNORECASE | re.MULTILINE)
row_original_text = re_compile.sub("", row_original_text, 1)
except Exception as e:
print(e)
# TODO handle
delta_text = row_original_text
delta_text = delta_text.lstrip()
if len(delta_text) > 50:
# remove different parts
#("It's my time. You don't want to find plenty of other outlets Will. Wait. I don't like you and I never will ponytail. I don't need you to like me. Sure. Guy. Draws better insults as you",
# "It's my time. You don't want to find plenty of other outlets Will. Wait. I don't like you and I never will ponytail. I don't need you to like me. Sure. Guy. After insults, as you are reporting. Come back tomorrow. Maybe I can teach you something. Do you know? There it is. All the kryptonite on earth. Thank you.")
#'GUY DRAWS BETTER INSULTS AS YOU'
#" ".join(existing_words[max([i for existing, row, i in zip(existing_words, row_words, range(0, 10000, 1)) if existing == row]):])
if len(frontload_latter_part) == 0:
print("DEBUG here")
last_match_word_count = max([i for existing, row, i in zip(frontload_latter_part, row_words, range(0, 10000, 1)) if existing == row]) + 1
delta_text = " ".join(row_words[last_match_word_count:])
# TODO: match with existing to get lower-case in caption_sub
print("do sometihng")
if len(front_load_part_string) == 0:
df_existing.at[index_existing, "text"] = row["text"]
else:
df_existing.at[index_existing, "text"] = front_load_part_string + " " + row["text"]
df_remove_list.append(index) # no additional entry needed in df
df_existing_sub_reference = df_existing_sub[df_existing_sub['start'] == row['start']][-1:]
if len(df_existing_sub_reference) == 0:
end_time = row['start']
else:
end_time = df_existing_sub_reference['end'].values[0] # substart
if row['text'] != delta_text:
tmp_se = pd.Series([
row['session'],
row['start'],
end_time,
row['end'],
row['actor'],
delta_text
], index=df_existing_sub_new.columns)
df_existing_sub_new = df_existing_sub_new.append(tmp_se, ignore_index=True)
else:
print("not exist")
df.drop(index=df_remove_list, inplace=True)
df_existing.drop(index=df_existing_remove_list, inplace=True)
# drop all
df_existing_sub.drop(index=[i for i, item in df_existing_sub.iterrows()], axis=1, inplace=True)
return df, df_existing,df_existing_sub,df_existing_sub_new
def update_captions_to_db(df:pd.DataFrame=None,df_existing:pd.DataFrame=None,
df_existing_sub:pd.DataFrame=None,
df_existing_sub_new:pd.DataFrame=None):
dbname = DB_NAME
conn = sqlite3.connect(dbname)
try:
if len(df) > 0:
for index, delete_item in df.iterrows():
conn.execute("DELETE FROM caption where " + \
"actor = '" + delete_item['actor'] + "' and " + \
"start = '" + datetime.datetime.strftime(delete_item['start'],"%Y-%m-%d %H:%M:%S.%f") + "' and " + \
"session = '" + delete_item['session'] + "'")
conn.commit()
df.to_sql('caption', conn, if_exists='append', index=False)
if len(df_existing) != 0:
for index, delete_item in df_existing.iterrows():
conn.execute("DELETE FROM caption where " + \
"id = '" + str(delete_item['id']) + "'")
conn.commit()
df_existing.drop(['id'],axis=1, inplace=True)
df_existing.to_sql('caption', con=conn, if_exists='append',index=False)
if len(df_existing_sub_new) > 0:
df_existing_sub_new.to_sql('caption_sub',conn,if_exists='append',index=False)
except Exception as e:
print(e)
conn.commit()
conn.close()
return
@app.route('/download_vocab_frequency',methods=['GET'])
def return_download_frequency():
if 'credentials' not in flask_session:
return flask_redirect("authorize")
received_session = request.args.get('session')
session_string = received_session
data_all = []
google_userid, google_part_of_email = get_user_id_from_session()
session_access_allowed,external_session_name = is_allowed_to_access(session_id=session_string,access_user=google_userid)
if google_userid is None:
return flask_redirect("authorize")
if session_access_allowed == False:
return f"No authorization to read session {session_string}"
df_freq = get_vocab_frequency(session_string=session_string,
google_userid=google_userid, google_part_of_email=google_part_of_email,
is_to_download=True)
if df_freq is None or len(df_freq) == 0:
return f"no data exists for session {session_string}"
resp = make_response(df_freq.to_csv(sep="\t"))
resp.headers["Content-Disposition"] = f"attachment; filename=session_frequency{session_string}.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
@app.route('/download_caption',methods=['GET'])
def return_download_caption():
if 'credentials' not in flask_session:
return flask_redirect("authorize")
received_session = request.args.get('session')
session_string = received_session
data_all = []
google_userid, google_part_of_email = get_user_id_from_session()
session_access_allowed,external_session_name = is_allowed_to_access(session_id=session_string,access_user=google_userid)
if google_userid is None:
return flask_redirect("authorize")
if session_access_allowed == False: