-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathielts_writing.py
3152 lines (2552 loc) · 189 KB
/
ielts_writing.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 streamlit as st
st.set_page_config(
page_title= 'IELTS Writing Evaluator'
# page_icon=
)
hide_st_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
</style>
"""
st.markdown(hide_st_style, unsafe_allow_html=True)
import anthropic
import google.generativeai as genai
from groq import Groq
from wordcloud import WordCloud, STOPWORDS
from PIL import Image
import matplotlib.pyplot as plt
import random
import re
import os
import csv
import time
import streamlit.components.v1 as components
import pyperclip
import replicate
import gspread
from google.oauth2.service_account import Credentials
from datetime import datetime, timedelta
from google.oauth2 import service_account
from openai import OpenAI
import time
from supabase import create_client, Client
from browser_detection import browser_detection_engine
# with open("BayanPlusTracking.html", "r") as f:
# html_code = f.read()
# components.html(html_code, height=0)
st.markdown(
"""
<style>
.st-emotion-cache-j7qwjs {
display: none;
}
.st-emotion-cache-sntl9t {
display: none;
}
.st-emotion-cache-1oe5cao {
display: none;
}
</style>
""",
unsafe_allow_html=True
)
st.markdown("""
<style>
.sidebar .sidebar-content {
transition: margin-left .3s;
}
.reportview-container .main .block-container {
max-width: 100%;
padding-left: 20rem;
transition: padding-left .3s;
}
.sidebar-expanded .sidebar .sidebar-content {
margin-left: 0;
}
.sidebar-expanded .reportview-container .main .block-container {
padding-left: 7rem;
}
</style>
""", unsafe_allow_html=True)
Claude_API_KEY = st.secrets['Claude_API_KEY']
Gemini_API_Key = st.secrets['Gemini_API_Key'] #mustafabinothman22
Gemini_API_Key2 = st.secrets['Gemini_API_Key2'] #mustafanotion
Gemini_API_Key3 = st.secrets['Gemini_API_Key3'] #mustafabinothman2003
Gemini_API_Key4 = st.secrets['Gemini_API_Key4'] #mustafabinothman2023
Gemini_API_Key5 = st.secrets['Gemini_API_Key5'] #www.binothman24
groq_API1 = st.secrets['groq_API1']
groq_API2 = st.secrets['groq_API2']
groq_API3 = st.secrets['groq_API3']
groq_API4 = st.secrets['groq_API4']
groq_API5 = st.secrets['groq_API6']
groq_API6 = st.secrets['groq_API6']
groq2_api1 = st.secrets['groq2_api1']
REPLICATE_API_TOKEN= st.secrets['REPLICATE_API_TOKEN']
YOUR_API_KEY = st.secrets['YOUR_API_KEY']
keys = [Gemini_API_Key,Gemini_API_Key2,Gemini_API_Key3,Gemini_API_Key4,Gemini_API_Key5]
used_key = random.choice(keys)
llama = "llama3-70b-8192"
# mixtral = "mixtral-8x7b-32768"
model = genai.GenerativeModel('gemini-1.0-pro-latest')
model_vision = genai.GenerativeModel('gemini-pro-vision')
type_check = 'primary'
type_take = 'secondary'
# ----------------------------- supabase info ----------------------------------------
url = "https://twrfzriopjdkicchfqzs.supabase.co"
key = st.secrets['supabase']
supabase: Client = create_client(url, key)
# "-------------------------------------------------------------------"
#google spreadsheet system
scopes = [
'https://www.googleapis.com/auth/spreadsheets'
]
credentials_json = {
"type": "service_account",
"project_id": "ielts-writing-evaluator",
"private_key_id": "a503f35fe20c737d9373cef7a6d450e26855faf0",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCrdr0FxPMPxx10\nBQcmsFciybuoUKO2nUlp5iRheaDOA//LB+wZBbNP1fj3+hj+ztL1zh992e91ny35\nruxiutMTh2iL1a/YLyUh7xBcH6japLZPoAUjjQHm7qS5RQtdftgKN2jJJ3R8STDd\nk1pbRwkrIWOhYwqeWHGzn/RO9IgwoSuHLRyuTLOKAg66q0un0GIt3xzA30d9Y5Lx\nfDH4QidW/VuU+ICfM/d/Op274yjtnDRt9g3DTT+i+vIf5IJDXej/Pew8KhSEXw9e\nFZjpueoZsDcBs2sABBr7xAyQH/xkn8z7mpM+99RMTUZX4HHVQLcrH+R6hpnYA7BO\n2tA0e/1rAgMBAAECggEAG3qZCn6o0YOApeJUZg/mtw2LhIr/4blNVaprdC+w5LNh\nYCFx5gSy2v2Yu+0Z6mQtDPWuuFWf+cK79ILjIWN9hmiyCY8CcmwD0G9muMzeG8Q/\n73zetfbYMjFWttZo3uAAMYr1wR8QnQaBzVDbLzuwLXhZZjjgL8ZO2pGs7qZj2R8H\ngn1qMof5x91hqyjyk30MS35tX3lCyex0Zi0WDC7h+dcMkt5kyX3s0vbizrC3Q+2L\njZrplSAUTW+wH1TOmdM39lx47ajOx+izsDFOfNpKL2OOfttG32/A7fW91lPWUQ0f\nWQa6QkrLw4SIok56l1CbHQysBDk0j8bu0I9Oal9oYQKBgQDvSJFNfX9+45Qhsoqa\nX4vI4uGbpwxGuzpPaKPYweZvsaitIb8zCd1yNJyy2HrhmWy3H+AdHQ+vpTvuY/oi\noNb0+v2fcP6gyjzKES6gaosQcuOq4IM69nVoK5l+d1q2GWuJyaA0hftA1Z8+qSUE\niVfLU0FaA6+XX2XskE8IXJMGkQKBgQC3cUJ2QFLXNEH3c1u1V5WAWFqdviNhyWsw\nBR3CmVGAM6Zfevm+fIhCoZ1czFx1VMyqZKtGXyyWdkzVTRa2Jani5FXEMta3o9Hl\nJcg38DwoUHLBpRTYvJftZA0dwV+YUKD8MK8xlNzv7kzSpg1f8dGb+mNaZrkoISA/\noBNZb+LaOwKBgQDaaeXf0rcG7tqu65bilGY25wnCF3f4NDxkcYJlf5BE0ejCp/Qr\ntUyCS43hHgMEXBRFD351dKp1zKBo2K9g3ml30oag+/YgdJmKZKan3Li1OfmgZzDC\nKGdAv9NrAa02XPuxGO74IngWVSf3fVOB0Y/m00bq0ER+KqERjyPk4QN/UQKBgQCH\nVyiR1iNIY2XIC3Q99sB2ULmKaB3yp4hNhXjPeg6HZ5P4HeLkhzyA7HwNWzlb15So\nol07LjzXRbCqLpXzDRaqL4yXlGqWUmcpiRaPLs8zbyc7d3BJ99qfapHCwkilN9eO\nON0I16up2UcUoy56+w6K5dEngWJaGRaR2qhr9ACKwQKBgQCnaD+295ZQR3D+zS1h\nqnUVdxDvCIuAEiC6UTiZIxHMW4p6CkyW7Oxv+rZENEexh4BCClIA2wvP9OvQbxUe\nWR8iUS0lKQ8yZ3S+1dLLhzhSJn+Y6gdskfAu69y3/a98nM9GvI3J/NgG71HrbPCK\nidCVD+IWMS5EqnaYMVrJSRUgbw==\n-----END PRIVATE KEY-----\n",
"client_email": "user-registration@ielts-writing-evaluator.iam.gserviceaccount.com",
"client_id": "104756563010734258293",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/user-registration%40ielts-writing-evaluator.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
# json_string = json.dumps(credentials_json,ensure_ascii=False, indent=4)
# creds = Credentials.from_service_account_file('credentials.json', scopes=scopes)
# creds = Credentials.from_service_account_file(credentials_json, scopes=scopes)
creds = service_account.Credentials.from_service_account_info(credentials_json, scopes=scopes)
# creds = Credentials.from_service_account_file(st.secrets["credentials_json"], scopes=scopes)
client = gspread.authorize(creds)
# gsheets = GSheetsConnection(credentials_json)
# Sheet IDs
free_trial_id = '18Cc9ITOYVEvmkhjQbNXgA6NxARPtFB_bHgN4ERozfXI'
subscription_id = '12Z_BTDGHPgITYV7XOMObLv17Ckt1pzUPYt4Uu_De2us'
progression_file_id = '1yCimM9WMtDdXEjJPMm9SX9blvQx541tFDKRiL0upovA'
essay_file_id = '1TD000SU1S2RqJp99e9fMeR-M8UsyCOdTXInqFgQpnR0'
all_essays_file_id = "1-_fGuj3WVyR2rhDsRaKOzKVAJW7Vxuy5D6Oacm1pHjA"
def get_location():
import requests
# Geoapify endpoint for IP Geolocation
try:
api_key2 = 'f26824af9014439a984af8b3a32538d2'
url = f"https://api.geoapify.com/v1/ipinfo?apiKey={api_key2}"
# Make the request
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# Extract IP address, city, and country from the response
# ip_address = data.get('ip', 'Unknown')
city = data['city']['name'] if 'city' in data and 'name' in data['city'] else "Unknown"
country = data['country']['name'] if 'country' in data and 'name' in data['country'] else "Unknown"
return city, country
else:
return "Unknown", "Unknown"
except Exception as e:
print(e)
# from browser_detection import browser_detection_engine
# def get_device_type():
# try:
# browser_stats = browser_detection_engine()
# print(browser_stats)
# if 'isDesktop' in browser_stats and browser_stats['isDesktop']:
# return 'Desktop'
# elif 'isMobile' in browser_stats and browser_stats['isMobile']:
# return 'Mobile'
# else:
# return 'Unknown'
# except Exception as e:
# print(e)
# return 'Unknown'
# Function to check if an email exists in a given sheet
def email_exists(table_name, email): #supabase
response = supabase.table(table_name).select('email').eq('email', email).execute()
data = response.data
return len(data) > 0
# Function to find the next empty row and add data
def add_user(email, number): #supabase
# Get the current date in the format you specified
current_date = datetime.now().strftime('%Y-%m-%d') # Supabase expects date in 'YYYY-MM-DD' format
try:
# Insert the new user into the specified table
response = supabase.table("free_trial").insert({
"email": email,
"attempts": number,
"date_of_registration": current_date,
# "last_used_date": current_date, # Assuming you want to set the last used date to the current date as well
# "country": None, # Assuming these fields are optional and can be updated later
# "city": None
}).execute()
print(f"User {email} added successfully. \n {response}")
except Exception as e:
print(f"An error occurred: {e}")
def check_language_exists(email):
result = supabase.table('free_trial').select('language').eq('email', email).execute()
if result.data and result.data[0]['language']:
return True
return False
def add_language_to_database(email, language):
print("add_language_to_database")
try:
result = supabase.table('free_trial').update({'language': language}).eq('email', email).execute()
if result.data:
print("language added")
return True
return False
except Exception as e:
st.error(f"Error adding language to database: {str(e)}")
return False
def add_location_and_device(email, country, city): #supabase
try:
# Update the user's country and city in the free_trial table
supabase.table('free_trial').update({
"country": country,
"city": city
}).eq('email', email).execute()
except Exception as e:
print(f"An error occurred: {e}")
# Function to validate Gmail email
def is_valid_gmail(email):
# first it should validate the email there are many websites can do that
# also detecting ip adress
gmail_regex = re.compile(r'^[a-zA-Z0-9._%+-]+@gmail\.com$')
return gmail_regex.match(email) is not None
def is_real_gmail(email):
import re
import requests
import json
import random
# Check if the email format is valid for Gmail
# gmail_regex = re.compile(r'^[a-zA-Z0-9._%+-][email protected]$')
# if not gmail_regex.match(email):
# return False
# Verify if the email address is real and can receive emails
api_keys = [
"9eeb2de334c441fbbd14272c1299190a",
"0dced7e2a5704d629c0662d175ff442d",
"ecdc73a6d6fe4924bf391cc7346f34df"
]
retries = 5
while retries > 0:
api_key = random.choice(api_keys)
try:
url = "https://emailvalidation.abstractapi.com/v1"
querystring = {"api_key": api_key, "email": email}
response = requests.get(url, params=querystring)
data = response.json()
deliverability = data.get("deliverability")
if deliverability == "DELIVERABLE":
return True
elif deliverability == "UNDELIVERABLE":
return False
except Exception as e:
print(f"Error verifying email with API key {api_key}: {e}")
# remember to send an email if the erorr happened
retries -= 1
return True
# def select_language(email):
# if 'language_selected' not in st.session_state:
# st.session_state.language_selected = False
# if not st.session_state.language_selected:
# st.write("Please select your native language:")
# selected_language = st.selectbox("Native Language", common_languages, key="language_selectbox")
# if st.button("Confirm Language"):
# if add_language_to_database(email, selected_language):
# st.session_state.language_selected = True
# st.success(f"Your native language ({selected_language}) has been added to your profile.")
# else:
# st.error("Failed to add language to the database. Please try again.")
# else:
# st.success("Your native language has been recorded.")
registred = False
def registration_process(email):
global registred
try:
city, country = get_location()
# Check if the email exists in the subscription table
if email_exists('subscriptions', email):
st.write('You are subscribed')
registred = True
else:
# Check if the email exists in the free_trial table
if email_exists('free_trial', email):
# st.write(f'{email} already exists in the Free Trial.')
add_location_and_device(email, country, city)
registred = True
else:
if is_real_gmail(email):
st.write("Email is real")
add_user(email, 5)
add_location_and_device(email, country, city)
st.success('Registered successfully!')
# st.write(f"{email} Registered successfully")
registred = True
else:
st.error('Invalid Gmail address. Please use a real Gmail account')
st.stop()
if remove_duplicate_emails(email):
st.write('Duplicate entries found and removed.')
except Exception as e:
st.error(f"Error during registration process: {str(e)}")
st.stop()
def append_score_and_date(email, task_type, score, date):
try:
# Convert the date to the correct format for timestamptz
date = datetime.strptime(date, '%d/%m/%Y %H:%M').strftime('%Y-%m-%d %H:%M:%S')
# Determine the column names based on the task type
if task_type == 'Task 1':
score_col = 'task_1_score'
date_col = 'task_1_date'
elif task_type == 'Task 2':
score_col = 'task_2_score'
date_col = 'task_2_date'
else:
return False # Invalid task type
# Insert a new record with the provided score and date
supabase.table('progression').insert({
"email": email,
score_col: score,
date_col: date,
"overall_score": None, # Set to None to avoid violating NOT NULL constraint
"overall_date": None # Set to None to avoid violating NOT NULL constraint
}).execute()
return True
except Exception as e:
print(f"An error occurred: {e}")
return False
if 'task1_band_score' not in st.session_state:
st.session_state['task1_band_score'] = []
if 'task2_band_score' not in st.session_state:
st.session_state['task2_band_score'] = []
def add_overall_score_to_progression_sheet(email, date):
if 'task1_band_score' in st.session_state and 'task2_band_score' in st.session_state:
task1_scores = st.session_state['task1_band_score']
task2_scores = st.session_state['task2_band_score']
print(task1_scores)
print(task2_scores)
if len(task1_scores) == 4 and len(task2_scores) == 4: # Check if both tasks have exactly 4 values
# overall_score_task1 = calculate_overall_score(task1_scores)
# overall_score_task2 = calculate_overall_score(task2_scores)
# overall_score = calculate_overall_score([overall_score_task1, overall_score_task2])
average_score = sum(task1_scores) / len(task2_scores)
# Append the overall score and date to the user's sheet
overall_score = round(average_score * 2) / 2
append_overall_score_and_date(email, float(overall_score), date)
st.markdown(f'\n\n#### After evaluating Task 1 and Task2 essays \n')
st.markdown(f"#### your overall band score is {(overall_score)}")
return True
else:
print("Each task must have exactly 4 values.")
return False
else:
print("Task scores are not available.")
return False
def append_overall_score_and_date(email, overall_score, date): #supabae
try:
# Check if the user already has an entry in the progression table
response = supabase.table('progression').select('*').eq('email', email).execute()
data = response.data
if data:
# If the user already has an entry, update the existing record
supabase.table('progression').update({
"overall_score": overall_score,
"overall_date": date
}).eq('email', email).execute()
else:
# If the user does not have an entry, insert a new record
supabase.table('progression').insert({
"email": email,
"overall_score": overall_score,
"overall_date": date
}).execute()
return True
except Exception as e:
print(f"An error occurred: {e}")
return False
#supabae
def append_evaluation_result(email, date, task_type, question, essay, task_response, coherence_cohesion, lexical_resources, grammar_accuracy, grammar_spelling, synonyms, rewritten_essay, score):
try:
# Convert the date to the correct format for timestamptz
date = datetime.strptime(date, '%d/%m/%Y %H:%M').strftime('%Y-%m-%d %H:%M:%S')
# Insert the evaluation results into the all_essays table
supabase.table('all_essays').insert({
"email": email,
"date": date,
"task_type": task_type,
"question": question,
"essay": essay,
"task_response": task_response,
"coherence_cohesion": coherence_cohesion,
"lexical_resource": lexical_resources,
"grammar_accuracy": grammar_accuracy,
"grammar_spelling": grammar_spelling,
"synonyms": synonyms,
"rewritten_essay": rewritten_essay,
"overall_score": score
}).execute()
return True
except Exception as e:
print(f"An error occurred: {e}")
return False
#supabae
def append_evaluation_result_to_all_essays(all_essays_file, email, date, task_type, question, essay, task_response, coherence_cohesion, lexical_resources, grammar_accuracy, grammar_spelling2, synonyms, rewritten_essay, score):
# Assuming the first sheet in the all_essays file is the one where you want to append the results
all_essays_sheet = all_essays_file.get_worksheet(0) # Adjust the index if the target sheet is not the first one
# Append the evaluation results and other details to the sheet
all_essays_sheet.append_row([email, date, task_type, question, essay, task_response, coherence_cohesion, lexical_resources, grammar_accuracy, grammar_spelling2, synonyms, rewritten_essay, score])
return True
def remove_duplicate_emails(email): #supabase
try:
# Query the free_trial table to find all rows with the given email
response = supabase.table('free_trial').select('*').eq('email', email).execute()
rows = response.data
# If more than one matching row is found, remove duplicates
if len(rows) > 1:
# Keep the first occurrence and delete the rest
for row in rows[1:]:
supabase.table('free_trial').delete().eq('email', row['email']).eq('date_of_registration', row['date_of_registration']).execute()
return True
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
def update_evaluation_date(email): #supabase
current_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Supabase expects datetime in 'YYYY-MM-DD HH:MM:SS' format
try:
# Update the last_used_date for the specified email in the free_trial table
response = supabase.table('free_trial').update({
"last_used_date": current_date
}).eq('email', email).execute()
if response.data:
print("User last used date updated", current_date)
return True
else:
print("Email not found")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
# if email_exists(free_trial_sheet, email):
# # User is in free trial, subtract from the "attempts" column
# user_row = free_trial_sheet.row_values(free_trial_sheet.find(email).row)
# attempts = int(user_row[free_trial_sheet.find("attempts").col - 1])
# if attempts > 0:
# attempts -= 1
# free_trial_sheet.update_cell(free_trial_sheet.find(email).row, free_trial_sheet.find("attempts").col, attempts)
# else:
# st.error(f"{email} has no evaluation attempts left.")
# # elif attempts <= 0:
# # # Delete the row if attempts are 0 or less
# # row = free_trial_sheet.find(email).row
# # free_trial_sheet.delete_row(row)
# # st.title('Registration System')
# "-------------------------------------------------------------------------------------------"
# st.sidebar.title("""
# """)
st.sidebar.title('IELTS Writing Evaluator (Free)')
side_check_button3 = st.sidebar.button('Profile', type=type_take, use_container_width=True)
if side_check_button3:
st.switch_page("pages/profile.py")
# st.sidebar.write('This is currently in Beta version, and everyday it will be updated to reach better evalaution GOOD LUCK 😊⚡')
# st.sidebar.write('There will be many special features and big improvments coming soon😊')
side_check_button = st.sidebar.button('Check Your Essay', type=type_check, use_container_width=True)
# st.sidebar.write("If you want to calculate the overall band score of Task 1 and Task 2 press the button 👇")
side_check_button2 = st.sidebar.button('Overall Band Score Calculator', type=type_take, use_container_width=True)
if side_check_button2:
st.switch_page("pages/overall.py")
# st.page_link("pages/overall.py", label="IELTS Overall Band Score Calculater", icon="🔶")
side_check_button3 = st.sidebar.button('Progress Tracker', type=type_take, use_container_width=True)
if side_check_button3:
st.switch_page("pages/progression_track.py")
# side_take_button = st.sidebar.button("Take a Test (it's coming soon)", type=type_take, use_container_width=True, disabled=True)
message = """**Looking to evaluate your IELTS writing essays for free? Check out this website that uses AI to assess your work:** \n Website link: ielts-writing-ai.streamlit.app
"""
# Button in the sidebar to trigger the copy function
st.sidebar.write("Help others to improve their IELTS writing by sharing the website ")
# if st.sidebar.button('Share the website ', type=type_check):
# # Use pyperclip to copy the message to the clipboard
# pyperclip.copy(message)
# st.sidebar.success('Copied thanks for sharing my website')
st.sidebar.write('Now you can evaluate your essay via Telegram: https://t.me/ielts_writing2_bot')
st.sidebar.write("If there is any issue in the performance or any suggetions please contact me")
# st.sidebar.write("Email: [email protected]")
st.sidebar.write("Telegram: https://t.me/ielts_pathway")
st.sidebar.markdown("Developed by **Mustafa Bin Othman**")
st.sidebar.markdown("You can support my effort by buying me a coffee. ☕️ :heart: " + "[Please click here](https://ko-fi.com/mustafa_binothman)")
# cookies = EncryptedCookieManager(
# prefix="ielts", # Prefix for the cookies
# password="mustafa774206578" # Password to encrypt the cookies
# )
# if not cookies.ready():
# st.stop()
st.title('IELTS Writing Evaluator (Free)')
st.write('This is a high-quality AI that is competent in evaluating IELTS writing. It uses advanced LLMs to make a high efficient evaluation .')
email = st.text_input('Please enter your Gmail')
# st.warning('Please click the "Register" button to proceed.')
if 'user_exist' not in st.session_state:
st.session_state.user_exist = False
if 'registered_email' not in st.session_state:
st.session_state.registered_email = None
if st.button('Register'):
if email is not None and email.strip() != "":
# Display an animated spinner while processing
start_time = time.time()
with st.spinner('wait few seconds...'):
# time.sleep(13) # Simulating a long process, replace with actual registration process
if is_valid_gmail(email):
print(f"email is valid")
registration_process(email)
st.session_state.user_exist = True
st.session_state.registered_email = email
# cookies["email"] = email
# cookies.save()
# st.write("Email registered and saved in cookies!")
# Clear the spinner message once the registration is complete
st.empty()
end_time = time.time()
execution_time = (end_time - start_time)
print("time taken to register", round(execution_time), "seconds")
# print(user_exist)
# st.success('Registration successful!')
else:
st.empty()
st.error('Incorrect Gmail address.')
st.stop()
else:
st.error('Please enter your Gmail.')
st.stop()
# email = st.text_input('please enter your email')
# if st.button('Rigester'):
# if not is_valid_gmail(email):
# st.error('Please enter a valid Gmail email.')
# else:
# result = check_email(email)
# if result is True:
# st.success('Email already registered. You can use the website.')
# # Add your website functionality here
# elif result is False:
# st.success('Email registered successfully. You can now use the website.')
# # Add your website functionality here
# else:
# st.error('Invalid Gmail email. Please provide a valid Gmail address.')
task = ''
gen_acad = ''
# Check if user's language is already in the database
# if registred == True:
# if not check_language_exists(email):
# print("not check_language_exists")
# # select_language(email)
# else:
# st.success("Your native language is already recorded.")
select_task = st.selectbox('**Select the task**', ['Task 1', 'Task 2'])
if select_task == 'Task 1':
task = 'Task 1'
gen_aca = st.selectbox('**Academic or General essay**', ['Academic', 'General'])
gen_acad = gen_aca
if gen_acad == 'Academic':
chart_image = st.file_uploader('Upload Task 1 chart/map etc.. (optional)', type=['png', 'jpg'] )
st.write("if you have written your essay in a paper, take a photo and upload it 👇")
important_notes = st.expander("How it works", expanded=False)
with important_notes:
st.markdown("**1- Make sure you upload a high quality photo with clear font for better results**")
st.markdown("**2- After you upload the photo check the written essay and edit it if there any issues**")
st.markdown("**3- If one photo wasn't enough to upload all the essay you can cancel the photo and upload the other photos (it will automatically add the text with first one)**")
task_image= st.file_uploader('Please upload a photo of the essay', type=['png', 'jpg'] )
else:
st.write("if you have written your essay in a paper take a photo and upload it 👇")
important_notes = st.expander("How it works", expanded=False)
with important_notes:
st.markdown("**1- Make sure you upload a high quality photo with clear font for better results**")
st.markdown("**2- After you upload the photo check the written essay and edit it if there any issues**")
st.markdown("**3- If one photo wasn't enough to upload all the essay you can cancel the photo and upload the other photos (it will automatically add the text with first one)**")
task_image= st.file_uploader('Upload a photo of the essay', type=['png', 'jpg'] )
else:
task = 'Task 2'
st.write("if you have written your essay in a paper take a photo and upload it 👇")
important_notes = st.expander("How it works", expanded=False)
with important_notes:
st.markdown("**1- Make sure you upload a high quality photo with clear font for better results**")
st.markdown("**2- After you upload the photo check the written essay and edit it if there any issues**")
st.markdown("**3- If one photo wasn't enough to upload all the essay you can cancel the photo and upload the other photos (it will automatically add the text with first one)**")
task_image= st.file_uploader('Upload a photo of the essay', type=['png', 'jpg'] )
opus = "claude-3-opus-20240229"
sonnet = "claude-3-sonnet-20240229"
haiku = "claude-3-haiku-20240307"
overall_band_score = []
url = "https://ko-fi.com/mustafa_binothman"
number_of_tries_vision = 5
# st.components.v1.iframe(url, width=800, height=600)
def decripe_image(api, image):
image_prompt = 'only describe the image and do not add any additional information that the image do not present'
max_retries = number_of_tries_vision
retries = 0
while retries < max_retries:
try:
used_key = random.choice(keys)
print(used_key)
genai.configure(api_key=used_key)
model_vision = genai.GenerativeModel('gemini-pro-vision')
response2 = model_vision.generate_content([image_prompt, image])
response2.resolve()
describe = response2.text
return describe
# print('---------------')
# print(len(described_image))
break
except Exception as e:
retries+=1
print("An error has occurred:", e)
print("Retrying...")
continue
# described_image = decripe_image()
# print (described_image)
# print('----')
describe_image = ''
if task == 'Task 1' and gen_acad == 'Academic' :
if chart_image is not None:
image_pil = Image.open(chart_image)
# described_image = decripe_image(used_key, image_pil)
# describe_image += described_image
# print (described_image)
# print('----')
st.image(image_pil, width=500)
else:
pass
# decripe_image(used_key, image_pil)
value= ''
def essay_image(api_key, image_pil):
max_retries = number_of_tries_vision
retries = 0
while retries < max_retries:
try:
used_key = random.choice(keys)
print(used_key)
image_prompt = 'Please transcribe the text from the provided image without adding any additional information or making changes to the words. Ensure accuracy in detecting and reproducing the text exactly as it appears in the image, including any spelling mistakes. Your task is to strictly adhere to the content visible in the image and refrain from introducing any extraneous details or alterations to the text. if the text was not in english only write that the text is not in English language '
genai.configure(api_key=used_key)
model_vision = genai.GenerativeModel('gemini-pro-vision')
response2 = model_vision.generate_content([image_prompt, image_pil])
response2.resolve()
describe = response2.text
prompt_image = f"""
You will be given text extracted from one or more images, which together should form an IELTS essay.
Your task is to carefully analyze the extracted text from each image,
ignoring any text that is not part of the essay. It is crucial that you do not make any changes to the essay's content, including correcting spelling or grammar,
the extracted text is {describe}
Instructions:
1- Read through the extracted text from each provided image, looking for the main body of the IELTS essay.
2- Ignore any text that appears to be unrelated to the IELTS essay, such as:
a. Headers or footers containing page numbers, dates, or other irrelevant information.
b. Instructions or prompts related to the IELTS writing task.
c. Personal notes or comments not intended to be part of the essay.
d. Incomplete sentences or fragments that do not contribute to the essay's content.
3- If there is no unrelated text in the extracted text from the image and the entire text forms a complete IELTS essay, return the essay text as-is, without adding any additional information or making any changes to the content.
4- Do not make any changes to the essay's content, including correcting spelling, grammar, or punctuation errors. The essay should be preserved in its original form
"""
response = model.generate_content(prompt_image, stream=True)
response.resolve()
rewrite = response.text
return rewrite
break
except Exception as e:
retries+=1
print("An internal error has occurred:", e)
print("Retrying...")
continue
else:
st.error('ERORR!!!, please try again')
question = st.text_area(label='**Enter the question of the essay**')
# st.markdown('### Write the essay')
if 'essay' not in st.session_state:
st.session_state.essay = value
if 'image_processed' not in st.session_state:
st.session_state.image_processed = False
if task_image is not None:
if not st.session_state.image_processed or task_image != st.session_state.last_uploaded_image:
image_pil = Image.open(task_image)
extracted_text = essay_image(Gemini_API_Key, image_pil)
if st.session_state.essay:
st.session_state.essay = st.session_state.essay + '\n' + extracted_text
else:
st.session_state.essay = extracted_text
st.session_state.image_processed = True
st.session_state.last_uploaded_image = task_image
essay = st.text_area(label='**Write or paste the essay**', height=600, value=st.session_state.essay)
try:
num_words = len(essay.split())
q_words = len(question.split())
except Exception as e :
num_words = 0
st.write('Number of Words: ',num_words)
button = st.button('Evaluate')
grammar_check = ''
TR_task = ''
task_resp_1_aca = ''
task_resp_1_gen = ''
coherence = ''
lexic = ''
suggeted_score = ''
def is_valid_word(word):
# Check if the word is made up of English letters, numbers, or allowable punctuation
if re.fullmatch(r'[a-zA-Z0-9.,?!;:\'"\(\)\[\]{}\-_%]+', word):
return True
return False
def contains_no_urls(text):
# Check if the text contains URL patterns
if re.search(r'\bhttps?://|www\.\b', text):
return False
return True
def check_essay(essay):
# Normalize the text by replacing newlines with spaces
normalized_essay = essay.replace('\n', ' ')
# Check for URLs in the entire text first
if not contains_no_urls(normalized_essay):
return False
# Split the essay into words considering punctuation
words = re.findall(r'\b[\w.,?!;:\'"\(\)\[\]{}\-_%]+\b', normalized_essay)
# Check each word
for word in words:
if not is_valid_word(word):
print("the essay contains non-english words or links")
return False
return True
list_of_repeated_words = []
number_of_tries = 1
# functions
def words_charts():
from collections import Counter
# Remove punctuation and convert to lowercase
essay_cleaned = re.sub(r'[^\w\s]', '', essay).lower()
excluded_words = ['those','than','there','were','who','were','it','of','the','it','from','was','my','these', 'your', 'you', 'this', 'because', 'other', 'before', 'after', 'should', 'would', 'can', 'be', 'why', 'where', 'when', 'what', "don't", 'does', 'do', 'how', 'which', 'that', 'me', 'am', 'i', "hasn't", "havn't", 'we', 'they', 'she', 'he', 'us', 'our', 'its', 'their', 'them', 'her', 'him', 'his', 'while', 'it', 'while', 'about', 'are', 'is', 'has', 'have', 'at', 'in', 'on', 'of', 'to', 'from', 'for', 'with', 'by', 'as', 'and', 'or', 'but', 'nor', 'so', 'yet', 'the', 'a', 'an', 'not','afghanistan', 'albania', 'algeria', 'andorra', 'angola', 'antigua and barbuda', 'argentina', 'armenia', 'australia', 'austria', 'azerbaijan', 'bahamas', 'bahrain', 'bangladesh', 'barbados', 'belarus', 'belgium', 'belize', 'benin', 'bhutan', 'bolivia', 'bosnia and herzegovina', 'botswana', 'brazil', 'brunei', 'bulgaria', 'burkina faso', 'burundi', 'cabo verde', 'cambodia', 'cameroon', 'canada', 'central african republic', 'chad', 'chile', 'china', 'colombia', 'comoros', 'congo', 'costa rica', 'croatia', 'cuba', 'cyprus', 'czechia', 'denmark', 'djibouti', 'dominica', 'dominican republic', 'ecuador', 'egypt', 'el salvador', 'equatorial guinea', 'eritrea', 'estonia', 'eswatini', 'ethiopia', 'fiji', 'finland', 'france', 'gabon', 'gambia', 'georgia', 'germany', 'ghana', 'greece', 'grenada', 'guatemala', 'guinea', 'guinea-bissau', 'guyana', 'haiti', 'honduras', 'hungary', 'iceland', 'india', 'indonesia', 'iran', 'iraq', 'ireland', 'israel', 'italy', 'jamaica', 'japan', 'jordan', 'kazakhstan', 'kenya', 'kiribati', 'kuwait', 'kyrgyzstan', 'laos', 'latvia', 'lebanon', 'lesotho', 'liberia', 'libya', 'liechtenstein', 'lithuania', 'luxembourg', 'madagascar', 'malawi', 'malaysia', 'maldives', 'mali', 'malta', 'marshall islands', 'mauritania', 'mauritius', 'mexico', 'micronesia', 'moldova', 'monaco', 'mongolia', 'montenegro', 'morocco', 'mozambique', 'myanmar', 'namibia', 'nauru', 'nepal', 'netherlands', 'new zealand', 'nicaragua', 'niger', 'nigeria', 'north korea', 'north macedonia', 'norway', 'oman', 'pakistan', 'palau', 'palestine', 'panama', 'papua new guinea', 'paraguay', 'peru', 'philippines', 'poland', 'portugal', 'qatar', 'romania', 'russia', 'rwanda', 'saint kitts and nevis', 'saint lucia', 'saint vincent and the grenadines', 'samoa', 'san marino', 'sao tome and principe', 'saudi arabia', 'senegal', 'serbia', 'seychelles', 'sierra leone', 'singapore', 'slovakia', 'slovenia', 'solomon islands', 'somalia', 'south africa', 'south korea', 'south sudan', 'spain', 'sri lanka', 'sudan', 'suriname', 'sweden', 'switzerland', 'syria', 'tajikistan', 'tanzania', 'thailand', 'timor-leste', 'togo', 'tonga', 'trinidad and tobago', 'tunisia', 'turkey', 'turkmenistan', 'tuvalu', 'uganda', 'ukraine', 'united arab emirates', 'united kingdom', 'united states', 'uruguay', 'uzbekistan', 'vanuatu', 'vatican city', 'venezuela', 'vietnam', 'yemen', 'zambia', 'zimbabwe', 'africa', 'antarctica', 'asia', 'europe', 'north america', 'south america', 'australia', 'states', 'united','january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
# countries_and_continents = ['afghanistan', 'albania', 'algeria', 'andorra', 'angola', 'antigua and barbuda', 'argentina', 'armenia', 'australia', 'austria', 'azerbaijan', 'bahamas', 'bahrain', 'bangladesh', 'barbados', 'belarus', 'belgium', 'belize', 'benin', 'bhutan', 'bolivia', 'bosnia and herzegovina', 'botswana', 'brazil', 'brunei', 'bulgaria', 'burkina faso', 'burundi', 'cabo verde', 'cambodia', 'cameroon', 'canada', 'central african republic', 'chad', 'chile', 'china', 'colombia', 'comoros', 'congo', 'costa rica', 'croatia', 'cuba', 'cyprus', 'czechia', 'denmark', 'djibouti', 'dominica', 'dominican republic', 'ecuador', 'egypt', 'el salvador', 'equatorial guinea', 'eritrea', 'estonia', 'eswatini', 'ethiopia', 'fiji', 'finland', 'france', 'gabon', 'gambia', 'georgia', 'germany', 'ghana', 'greece', 'grenada', 'guatemala', 'guinea', 'guinea-bissau', 'guyana', 'haiti', 'honduras', 'hungary', 'iceland', 'india', 'indonesia', 'iran', 'iraq', 'ireland', 'israel', 'italy', 'jamaica', 'japan', 'jordan', 'kazakhstan', 'kenya', 'kiribati', 'kuwait', 'kyrgyzstan', 'laos', 'latvia', 'lebanon', 'lesotho', 'liberia', 'libya', 'liechtenstein', 'lithuania', 'luxembourg', 'madagascar', 'malawi', 'malaysia', 'maldives', 'mali', 'malta', 'marshall islands', 'mauritania', 'mauritius', 'mexico', 'micronesia', 'moldova', 'monaco', 'mongolia', 'montenegro', 'morocco', 'mozambique', 'myanmar', 'namibia', 'nauru', 'nepal', 'netherlands', 'new zealand', 'nicaragua', 'niger', 'nigeria', 'north korea', 'north macedonia', 'norway', 'oman', 'pakistan', 'palau', 'palestine', 'panama', 'papua new guinea', 'paraguay', 'peru', 'philippines', 'poland', 'portugal', 'qatar', 'romania', 'russia', 'rwanda', 'saint kitts and nevis', 'saint lucia', 'saint vincent and the grenadines', 'samoa', 'san marino', 'sao tome and principe', 'saudi arabia', 'senegal', 'serbia', 'seychelles', 'sierra leone', 'singapore', 'slovakia', 'slovenia', 'solomon islands', 'somalia', 'south africa', 'south korea', 'south sudan', 'spain', 'sri lanka', 'sudan', 'suriname', 'sweden', 'switzerland', 'syria', 'tajikistan', 'tanzania', 'thailand', 'timor-leste', 'togo', 'tonga', 'trinidad and tobago', 'tunisia', 'turkey', 'turkmenistan', 'tuvalu', 'uganda', 'ukraine', 'united arab emirates', 'united kingdom', 'united states', 'uruguay', 'uzbekistan', 'vanuatu', 'vatican city', 'venezuela', 'vietnam', 'yemen', 'zambia', 'zimbabwe', 'africa', 'antarctica', 'asia', 'europe', 'north america', 'south america', 'australia', 'states', 'united',]
# Split the essay into words and exclude words in the excluded_words list
words = [word for word in essay_cleaned.split() if word.lower() not in [w.lower() for w in excluded_words]]
# words = [word for word in essay_cleaned.split() if word not in countries_and_continents]
# Filter out numbers from the words list
words = [word for word in words if not word.isdigit()]
word_counts = Counter(words)
most_repeated_words = word_counts.most_common(5)
for word, count in most_repeated_words:
list_of_repeated_words.append(word)
st.markdown('**Top 5 Most Repeated Words**')
words = [word for word, _ in most_repeated_words]
counts = [count for _, count in most_repeated_words]
# Create a bar chart
plt.figure(figsize=(10, 6))
plt.bar(words, counts, color='skyblue')
plt.xlabel('Words')
plt.ylabel('Counts')
plt.title('Top 5 Most Repeated Words')
st.pyplot(plt)
def organaize_synonyms(API, synonyms):
sy_prompt = f"""
you will be given a list of words with their synonyms and your task is to organaize them and make them in markdown format
and i want it like this format below only write what you have been asked about do not write any other non-needed text i repeat only write what you have been asked about
the synonyms are: {synonyms}
**the word:**
- Synonym 1
- Synonym 2
- Synonym 3
"""
max_retries = number_of_tries
retries = 0
while retries < max_retries:
try:
print('organaize synonyms')
client = Groq(
api_key=groq_API3
)
chat_completion = client.chat.completions.create(
messages=[
# Set an optional system message. This sets the behavior of the
# assistant and can be used to provide specific instructions for
# how it should behave throughout the conversation.
{
"role": "system",
"content": "you are IELTS Expert ."
},
# Set a user message for the assistant to respond to.
{
"role": "user",
"content": sy_prompt,
}
],
model=llama,
)
synonyms = chat_completion.choices[0].message.content
st.markdown(synonyms)
return synonyms
break # Break out of the while loop if the generation is successful
except Exception as e:
print("An error has occurred:", e)
print("Retrying...")
continue
else:
try:
print("excute replicate API")
output = replicate.run(
"meta/meta-llama-3-70b-instruct",
input={'prompt':sy_prompt},
)
result = ("".join(output))
st.markdown(result)
return result
except Exception as e:
print("An error has occurred:", e)
print("Retrying...")
st.error("Sorry, there is an unexpected problem happened Please try again later, if the problem persists please contact me")
print("Sorry, there is an unexpected problem happened Please try again later, if the problem persists please contact me")
print("stop running replicate (organise synonyms)")
st.stop()
def synonym(API= groq_API1, model2=llama):
sy_prompt = f"""As an English language expert, your task is to provide three context-appropriate synonyms for each of the five words given from an IELTS writing essay from this repeated words {list_of_repeated_words} in this essay {essay}.
The synonyms should be carefully chosen to maintain the intended meaning of the words within the essay's context and to enhance the writing score.
Avoid repeating the same word or suggesting synonyms that do not fit the context.
Instructions:
1- Review the provided IELTS writing essay and the list of five repeated words.
2- For each word, provide three synonyms that are suitable for the word's intended meaning within the essay's context.
3- Ensure that the suggested synonyms are appropriate for IELTS writing and can help enhance the writing score.
4- Present the synonyms in the following format:
Word 1:
Synonym 1
Synonym 2
Synonym 3
Word 2:
Synonym 1
Synonym 2
Synonym 3
(Repeat the format for all five words)
5- If a word has no suitable synonyms that fit the context, skip that word and move on to the next one.
Remember to focus solely on providing context-appropriate synonyms without including any additional information unrelated to the task.
"""
max_retries = number_of_tries
retries = 0
while retries < max_retries:
try:
client = Groq(
api_key=API
)
chat_completion = client.chat.completions.create(
messages=[
# Set an optional system message. This sets the behavior of the
# assistant and can be used to provide specific instructions for
# how it should behave throughout the conversation.
{
"role": "system",
"content": "you are IELTS Expert ."
},
# Set a user message for the assistant to respond to.
{
"role": "user",
"content": sy_prompt,
}
],
model=model2,
)
synonyms = chat_completion.choices[0].message.content
return organaize_synonyms(API, synonyms)
break # Break out of the while loop if the generation is successful
except Exception as e:
print("An error has occurred:", e)
print("Retrying...")
continue
else:
try: