File size: 41,912 Bytes
e31495c
 
 
 
8fa7be2
e31495c
 
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
 
8fa7be2
e31495c
 
8fa7be2
 
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
 
8fa7be2
e31495c
 
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
8fa7be2
e31495c
8fa7be2
 
e31495c
8fa7be2
 
e31495c
 
 
8fa7be2
 
 
e31495c
 
 
8fa7be2
 
e31495c
 
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
8fa7be2
 
e31495c
8fa7be2
 
 
 
 
e31495c
8fa7be2
 
e31495c
 
 
8fa7be2
 
e31495c
 
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
8fa7be2
 
e31495c
8fa7be2
 
e31495c
8fa7be2
e31495c
 
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
 
 
 
 
8fa7be2
 
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
8fa7be2
 
e31495c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa7be2
e31495c
 
 
 
 
 
 
8fa7be2
 
e31495c
 
8fa7be2
e31495c
 
8fa7be2
 
e31495c
 
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
8fa7be2
e31495c
 
 
 
 
 
 
 
 
 
 
 
 
8fa7be2
 
e31495c
 
8fa7be2
e31495c
 
 
 
 
 
 
 
 
8fa7be2
 
 
e31495c
8fa7be2
 
e31495c
8fa7be2
 
e31495c
 
 
 
8fa7be2
 
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
8fa7be2
 
 
 
e31495c
 
 
 
 
8fa7be2
e31495c
8fa7be2
e31495c
 
 
 
 
8fa7be2
e31495c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa7be2
e31495c
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
 
 
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa7be2
 
e31495c
 
8fa7be2
e31495c
 
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
8fa7be2
 
e31495c
 
 
 
 
 
 
8fa7be2
e31495c
 
8fa7be2
e31495c
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
8fa7be2
 
e31495c
 
 
8fa7be2
e31495c
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa7be2
 
 
e31495c
 
 
 
 
 
 
 
 
 
 
 
 
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
# import os
# import base64
# from groq import Groq
# import streamlit as st

# class IELTSTask2Evaluator:
#     def __init__(self):
#         self.client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
#         self.model = "openai/gpt-oss-20b"

#     def evaluate_essay(self, essay_question, essay_content):
#         score_prompt = """ Provide the scores for the following IELTS task 2 essay in terms of Cohesion & Coherence, Task Achievement, Lexical Resouces and Grammatical Range & Accuracy critera. The scores should be in IELTS framework. Each criterion should be scored between 1 to 9 and should be integer. E.g. 5.5 is not acceptable! For each criteria that you score also provide 3 different comments using the following band descriptors and by referncing the essay.

#             IELTS Scoring band descriptor: 
#             Task Achievement: Score 9: •	fully addresses all parts of the task
#                                        •	presents a fully developed position in answer to the question with relevant, fully extended and well supported ideas

#                                     8:  •	sufficiently addresses all parts of the task
#                                         •	presents a well-developed response to the question with relevant, extended and supported ideas

#                                     7:  •	addresses all parts of the task
#                                         •	presents a clear position throughout the response
#                                         •	presents, extends and supports main ideas, but there may be a tendency to over-generalise and/or supporting ideas may lack focus
                                    
#                                     6:	•	addresses all parts of the task although some parts may be more fully covered than others
#                                         •	presents a relevant position although the conclusions may become unclear or repetitive
#                                         •	presents relevant main ideas but some may be inadequately developed/unclear
                                    
#                                     5:	•	addresses the task only partially; the format may be inappropriate in places
#                                         •	expresses a position but the development is not always clear and there may be no conclusions drawn
#                                         •	presents some main ideas but these are limited and not sufficiently developed; there may be irrelevant detail
                                    
#                                     4:	•	responds to the task only in a minimal way or the answer is tangential; the format may be inappropriate
#                                         •	presents a position but this is unclear
#                                         •	presents some main ideas but these are difficult to identify and may be repetitive, irrelevant or not well supported
                                    
#                                     3:	•	does not adequately address any part of the task
#                                         •	does not express a clear position
#                                         •	presents few ideas, which are largely undeveloped or irrelevant
                                    
#                                     2:	•	barely responds to the task
#                                         •	does not express a position
#                                         •	may attempt to present one or two ideas but there is no development
#                                     1:	•	answer is completely unrelated to the task

#              Cohesion and Coherence: Score 9:   •	uses cohesion in such a way that it attracts no attention
#                                                 •	skilfully manages paragraphing
                                            
                                            
#                                     Score 8:       •	sequences information and ideas logically
#                                             •	manages all aspects of cohesion well
#                                                 •	uses paragraphing sufficiently and appropriately
                                                
#                                                Score 7:  •	logically organises information and ideas; there is clear progression throughout
#                                                 •	uses a range of cohesive devices appropriately although there may be some under-/over-use
#                                                 •	presents a clear central topic within each paragraph
                                                
#                                             Score 6:     •	arranges information and ideas coherently and there is a clear overall progression
#                                                 •	uses cohesive devices effectively, but cohesion within and/or between sentences may be faulty or mechanical
#                                                 •	may not always use referencing clearly or appropriately
#                                                 •	uses paragraphing, but not always logically
                                                
#                                             Score 5:     •	presents information with some organisation but there may be a lack of overall progression
#                                                 •	makes inadequate, inaccurate or over-use of cohesive devices
#                                                 •	may be repetitive because of lack of referencing and substitution
#                                                 •	may not write in paragraphs, or paragraphing may be inadequate
                                                                                            
#                                             Score 4:     •	presents information and ideas but these are not arranged coherently and there is no clear progression in the response
#                                                 •	uses some basic cohesive devices but these may be inaccurate or repetitive
#                                                 •	may not write in paragraphs or their use may be confusing

#                                            Score 3:     •	does not organise ideas logically
#                                                 •	may use a very limited range of cohesive devices, and those used may not indicate a logical relationship between ideas
                                                
#                                              Score 2:    •	has very little control of organisational features
                                                
#                                               Score 1:   •	fails to communicate any message
                                            

#             Lexical Resouce:    Score 9:	•	uses a wide range of vocabulary with very natural and sophisticated control of lexical features; rare minor errors occur only as 'slips'
                                
                                
#                                 Score 8:	•	uses a wide range of vocabulary fluently and flexibly to convey precise meanings
#                                             •	skilfully uses uncommon lexical items but there may be occasional inaccuracies in word choice and collocation
#                                             •	produces rare errors in spelling and/or word formation
                                
                                
                                
#                                 Score 7:	•	uses a sufficient range of vocabulary to allow some flexibility and precision
#                                             •	uses less common lexical items with some awareness of style and collocation
#                                             •	may produce occasional errors in word choice, spelling and/or word formation
                                
                                
#                                 Score 6:	•	uses an adequate range of vocabulary for the task
#                                             •	attempts to use less common vocabulary but with some inaccuracy
#                                             •	makes some errors in spelling and/or word formation, but they do not impede communication
                                
                                
#                                 Score 5:	•	uses a limited range of vocabulary, but this is minimally adequate for the task
#                                 •	may make noticeable errors in spelling and/or word formation that may cause some difficulty for the reader
                                
                                
#                                 Score 4:	•	uses only basic vocabulary which may be used repetitively or which may be inappropriate for the task
#                                 •	has limited control of word formation and/or spelling; errors may cause strain for the reader
                                
                                
#                                 Score 3:	•	uses only a very limited range of words and expressions with very limited control of word formation and/or spelling
#                                 •	errors may severely distort the message
                                
                                
#                                 Score 2:	•	uses an extremely limited range of vocabulary; essentially no control of word formation and/or spelling
                                
                                
#                                 Score 1:	•	can only use a few isolated words





#         Grammatical Range and Accuracy:  Score 9:	•	uses a wide range of structures with full flexibility and accuracy; rare minor errors occur only as 'slips'
                                        
                                        
#                                         Score 8:	•	uses a wide range of structures
#                                         •	the majority of sentences are error-free
#                                         •	makes only very occasional errors or inappropriacies
                                        
                                        
#                                         Score 7:	•	uses a variety of complex structures
#                                         •	produces frequent error-free sentences
#                                         •	has good control of grammar and punctuation but may make a few errors
                                        
                                        
#                                         Score 6:	•	uses a mix of simple and complex sentence forms
#                                         •	makes some errors in grammar and punctuation but they rarely reduce communication
                                        
                                        
#                                         Score 5:	•	uses only a limited range of structures
#                                         •	attempts complex sentences but these tend to be less accurate than simple sentences
#                                         •	may make frequent grammatical errors and punctuation may be faulty; errors can cause some difficulty for the reader
                                        
                                        
#                                         Score 4:	•	uses only a very limited range of structures with only rare use of subordinate clauses
#                                         •	some structures are accurate but errors predominate, and punctuation is often faulty
                                        
                                        
#                                         Score 3:	•	attempts sentence forms but errors in grammar and punctuation predominate and distort the meaning
                                        
                                        
#                                         Score 2:	•	cannot use sentence forms except in memorised phrases
                                        
                                        
#                                         Score 1:	•	cannot use sentence forms at all
            
#             Essay Question: {}
#             Essay: {}
#             """
#         return self._get_completion(score_prompt.format(essay_question, essay_content))

#     def analyze_grammar(self, essay_content):
#         gram_prompt = """ Provide a grammatical analysis of the following essay with respect to the content a B1 leanrner must know. Provide all the grammars used and their accuracy pecentage. E.g. "Simple Present: 70%". Also provide comments for inaccurate structures. Don't give me any exercises.

#     Essay: {}
#     """
#         return self._get_completion(gram_prompt.format(essay_content))

#     def analyze_vocabulary(self, essay_content):
#         vocab_prompt = """ Provide the lexical errors and provide their correct forms. For each of the vocabulary related to the context of the essay that you think could be improved, give suggesions. Provide full sentence examples for these suggestions.

#     Essay: {}
#     """
#         return self._get_completion(vocab_prompt.format(essay_content))

#     def analyze_cohesion_coherence(self, essay_content):
#         coh_coh_prompt = """ Evaluate the cohesion and coherence of essay based on the following aspects. DO NOT SCORE THEM:

#     - paraphrasing ability
#     - logical sequencing of ideas
#     - use and accuracy of cohesive devices
#     - existence of a clear central topic in each paragrpah
#     - correct paragraphing
    
    
#     Essay: {}
#     """
#         return self._get_completion(coh_coh_prompt.format(essay_content))

#     def analyze_task_achievement(self, essay_question, essay_content):
#         task_ach_prompt = """ Evaluate the Task Achievement factor of this IELTS essay based on the following question and essay. Do NOT provide scores. Just mention analysis and how it could be imporved.

#     Question: {}
    
    
#     Essay: {}
#     """
#         return self._get_completion(task_ach_prompt.format(essay_question, essay_content))

#     def _get_completion(self, prompt):
#         response = self.client.chat.completions.create(
#             messages=[{"role": "user", "content": prompt}],
#             model=self.model
#         )
#         return response.choices[0].message.content


# class IELTSTask2ExerciseGenerator:
#     def __init__(self):
#         self.client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
#         self.model = "llama3-8b-8192"

#     def generate_grammar_exercises(self, grammar_analysis, essay_content):
#         gram_exer_prompt = """ Based on the content of the grammar analysis provided in JSON format, make 4 different exercise types and provide 10 exercises for each. All the items should be in the context of the essay. Avoid providing exercises that are exact replica of the candidates' mistakes.

#     Grammar Analysis: {}
    
#     Essay: {}
#     """
#         return self._get_completion(gram_exer_prompt.format(grammar_analysis, essay_content))

#     def generate_vocabulary_exercises(self, vocab_analysis):
#         vocab_exer_prompt = """ Based on the lexical errors, provide exercises in the same context of the essay. Avoid providing exercises that are exact replica of the candidates' mistakes.

#     Lexical Errors: {}
#     """
#         return self._get_completion(vocab_exer_prompt.format(vocab_analysis))

#     def _get_completion(self, prompt):
#         response = self.client.chat.completions.create(
#             messages=[{"role": "user", "content": prompt}],
#             model=self.model
#         )
#         return response.choices[0].message.content


# class IELTSTask1Evaluator:
#     def __init__(self):
#         self.client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
#         self.text_model = "llama3-8b-8192"
#         self.vision_model = "llama-3.2-11b-vision-preview"

#     def encode_image(self, image_path):
#         with open(image_path, "rb") as image_file:
#             return base64.b64encode(image_file.read()).decode('utf-8')

#     def analyze_graph(self, image_path, question):
#         """Analyzes the graph/chart provided for Task 1 considering the question"""
#         base64_image = self.encode_image(image_path)
#         response = self.client.chat.completions.create(
#             messages=[
#                 {
#                     "role": "user",
#                     "content": [
#                         {
#                             "type": "text", 
#                             "text": f"""Given this IELTS Task 1 question: {question}
                            
#                             Please analyze the graph/chart and:
#                             1. List the key features that need to be described based on the question requirements
#                             2. Identify the main trends, patterns, or comparisons required by the question
#                             3. Note any significant data points that should be highlighted
#                             4. Specify what should be included in the overview
#                             5. Indicate what details should be included in the body paragraphs
                            
#                             Provide your analysis in a structured format that can be used to evaluate student responses."""
#                         },
#                         {
#                             "type": "image_url",
#                             "image_url": {
#                                 "url": f"data:image/jpeg;base64,{base64_image}",
#                             },
#                         },
#                     ],
#                 }
#             ],
#             model=self.vision_model,
#         )
#         return response.choices[0].message.content
        
#     def evaluate_task1_response(self, question, graph_analysis, written_response):
#         score_prompt = """Provide the scores for the following IELTS Task 1 essay based on the graph analysis provided and the written response. Score in terms of Task Achievement, Coherence and Cohesion, Lexical Resource, and Grammatical Range & Accuracy criteria. The scores should be in IELTS framework. Each criterion should be scored between 1 to 9 and should be integer. E.g. 5.5 is not acceptable! For each criteria that you score, provide 3 different comments using the band descriptors and by referencing both the key features of the graph and how well they were described in the response.
#         IELTS Task 1 Band Descriptors:

# Band 9:
# • Fully satisfies all requirements of the task
# • Clearly presents a fully developed response
# • Uses cohesion in such a way that it attracts no attention
# • Skilfully manages paragraphing
# • Uses a wide range of vocabulary with very natural and sophisticated control of lexical features; rare minor errors occur only as 'slips'
# • Uses a wide range of structures with full flexibility and accuracy; rare minor errors occur only as 'slips'

# Band 8:
# • Covers all requirements of the task sufficiently
# • Presents, highlights and illustrates key features/bullet points clearly and appropriately
# • Sequences information and ideas logically
# • Manages all aspects of cohesion well
# • Uses paragraphing sufficiently and appropriately
# • Uses a wide range of vocabulary fluently and flexibly to convey precise meanings
# • Skilfully uses uncommon lexical items but there may be occasional inaccuracies in word choice and collocation
# • Produces rare errors in spelling and/or word formation
# • Uses a wide range of structures
# • The majority of sentences are error-free
# • Makes only very occasional errors or inappropriacies

# Band 7:
# • Covers the requirements of the task
# • Presents a clear overview of main trends, differences or stages
# • Clearly presents and highlights key features/bullet points but could be more fully extended
# • Logically organises information and ideas; there is clear progression throughout
# • Uses a range of cohesive devices appropriately although there may be some under-/over-use
# • Uses a sufficient range of vocabulary to allow some flexibility and precision
# • Uses less common lexical items with some awareness of style and collocation
# • May produce occasional errors in word choice, spelling and/or word formation
# • Uses a variety of complex structures
# • Produces frequent error-free sentences
# • Has good control of grammar and punctuation but may make a few errors
        
#         Band 6:
# • Addresses the requirements of the task
# • Presents an overview with information appropriately selected
# • Presents and adequately highlights key features/bullet points but details may be irrelevant, inappropriate or inaccurate
# • Arranges information and ideas coherently and there is a clear overall progression
# • Uses cohesive devices effectively, but cohesion within and/or between sentences may be faulty or mechanical
# • May not always use referencing clearly or appropriately
# • Uses an adequate range of vocabulary for the task
# • Attempts to use less common vocabulary but with some inaccuracy
# • Makes some errors in spelling and/or word formation, but they do not impede communication
# • Uses a mix of simple and complex sentence forms
# • Makes some errors in grammar and punctuation but they rarely reduce communication

# Band 5:
# • Generally addresses the task; the format may be inappropriate in places
# • Recounts detail mechanically with no clear overview; there may be no data to support the description
# • Presents, but inadequately covers, key features/bullet points; there may be a tendency to focus on details
# • Presents information with some organisation but there may be a lack of overall progression
# • Makes inadequate, inaccurate or over-use of cohesive devices
# • May be repetitive because of lack of referencing and substitution
# • Uses a limited range of vocabulary, but this is minimally adequate for the task
# • May make noticeable errors in spelling and/or word formation that may cause some difficulty for the reader
# • Uses only a limited range of structures
# • Attempts complex sentences but these tend to be less accurate than simple sentences
# • May make frequent grammatical errors and punctuation may be faulty; errors can cause some difficulty for the reader

# Band 4:
# • Attempts to address the task but does not cover all key features/bullet points; the format may be inappropriate
# • May confuse key features/bullet points with detail; parts may be unclear, irrelevant, repetitive or inaccurate
# • Presents information and ideas but these are not arranged coherently and there is no clear progression
# • Uses some basic cohesive devices but these may be inaccurate or repetitive
# • Uses only basic vocabulary which may be used repetitively or which may be inappropriate for the task
# • Has limited control of word formation and/or spelling; errors may cause strain for the reader
# • Uses only a very limited range of structures with only rare use of subordinate clauses
# • Some structures are accurate but errors predominate, and punctuation is often faulty

# Band 3:
# • Fails to address the task, which may have been completely misunderstood
# • Presents limited ideas which may be largely irrelevant/repetitive
# • Does not organise ideas logically
# • May use a very limited range of cohesive devices, and those used may not indicate a logical relationship between ideas
# • Uses only a very limited range of words and expressions with very limited control of word formation and/or spelling
# • Errors may severely distort the message
# • Attempts sentence forms but errors in grammar and punctuation predominate and distort the meaning

# Band 2:
# • Answer is barely related to the task
# • Has very little control of organisational features
# • Uses an extremely limited range of vocabulary; essentially no control of word formation and/or spelling
# • Cannot use sentence forms except in memorised phrases

# Band 1:
# • Answer is completely unrelated to the task
# • Fails to communicate any message
# • Can only use a few isolated words
# • Cannot use sentence forms at all

# Band 0:
# • Does not attend
# • Does not attempt the task in any way
# • Writes a totally memorised response
#         Question: {}
#         Graph Analysis: {}
#         Written Response: {}
#         """
#         return self._get_completion(score_prompt.format(question, graph_analysis, written_response))

#     def analyze_grammar(self, written_response):
#         gram_prompt = """Provide a grammatical analysis of the following Task 1 response with respect to describing trends, comparisons, and data. Provide all the grammars used and their accuracy percentage. E.g. "Past tense: 70%". Also provide comments for inaccurate structures. Focus especially on:
#         - Tense usage for trends
#         - Comparative structures
#         - Passive voice
#         - Articles with data
#         - Prepositions with trends

#         Response: {}
#         """
#         return self._get_completion(gram_prompt.format(written_response))

#     def analyze_vocabulary(self, written_response):
#         vocab_prompt = """Analyze the vocabulary used in this Task 1 response, focusing on:
#         - Language for describing trends
#         - Comparison vocabulary
#         - Data reporting vocabulary
#         - Graph/chart-specific terminology
#         Provide suggestions for improvement with examples in similar contexts.
        
#         Response: {}
#         """
#         return self._get_completion(vocab_prompt.format(written_response))

#     def analyze_task_achievement(self, question, graph_analysis, written_response):
#         task_ach_prompt = """Compare the key features identified in the graph analysis with how they were covered in the written response. Evaluate:
#         - Overview presence and quality
#         - Key feature selection
#         - Data accuracy
#         - Trend description completeness
#         Do NOT provide scores, only analysis and suggestions for improvement.

#         Question: {}
#         Graph Analysis: {}
#         Written Response: {}
#         """
#         return self._get_completion(task_ach_prompt.format(question, graph_analysis, written_response))

#     def analyze_cohesion_coherence(self, written_response, graph_analysis):
#         coh_coh_prompt = """Evaluate the cohesion and coherence of essay based on the following aspects. DO NOT SCORE THEM:
#         - paraphrasing ability
#         - logical sequencing of ideas
#         - use and accuracy of cohesive devices
#         - existence of a clear central topic in each paragraph
#         - correct paragraphing
        
#         Graph Analysis: {}
#         Response: {}
#         """
#         return self._get_completion(coh_coh_prompt.format(graph_analysis, written_response))
    
#     def _get_completion(self, prompt):
#         response = self.client.chat.completions.create(
#             messages=[{"role": "user", "content": prompt}],
#             model=self.text_model
#         )
#         return response.choices[0].message.content
    
    

# class IELTSTask1ExerciseGenerator:
#     def __init__(self):
#         self.client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
#         self.model = "llama3-8b-8192"

#     def generate_grammar_exercises(self, grammar_analysis, essay_content):
#         gram_exer_prompt = """ Based on the content of the grammar analysis provided in JSON format, make 4 different exercise types and provide 10 exercises for each. All the items should be in the context of the essay. Avoid providing exercises that are exact replica of the candidates' mistakes.

#     Grammar Analysis: {}
#     Essay: {}
#     """
#         return self._get_completion(gram_exer_prompt.format(grammar_analysis, essay_content))
    
#     def generate_graph_description_exercises(self, graph_analysis):
#         exercise_prompt = """Based on the graph analysis provided, create exercises to practice:
# 1. Writing overviews (1 exercise)
# 2. Describing trends (1 exercise)
# 3. Comparing data points (1 exercises)
# 4. Selecting key features (1 exercises)

# Keep all exercises relevant to the graph context.

# Graph Analysis: {}
# """
#         return self._get_completion(exercise_prompt.format(graph_analysis))

#     def generate_vocabulary_exercises(self, vocab_analysis):
#         vocab_prompt = """Create targeted vocabulary exercises for Task 1 writing based on the vocabulary analysis. Include:
# 1. Trend description vocabulary
# 2. Comparison language
# 3. Data reporting phrases
# 4. Graph-specific terminology

# Analysis: {}
# """
#         return self._get_completion(vocab_prompt.format(vocab_analysis))

#     def _get_completion(self, prompt):
#         response = self.client.chat.completions.create(
#             messages=[{"role": "user", "content": prompt}],
#             model=self.model
#         )
#         return response.choices[0].message.content


# def llm_responder_t1(image_path, question, written_response):
#     task1_evaluator = IELTSTask1Evaluator()
#     task1_generator = IELTSTask1ExerciseGenerator()
#     graph_analysis = task1_evaluator.analyze_graph(image_path)
#     general_analysis = task1_evaluator.evaluate_essay(question, graph_analysis, written_response)
#     ga =  task1_evaluator.analyze_grammar(written_response)
#     lr =  task1_evaluator.analyze_vocabulary(written_response)
#     ta =  task1_evaluator.analyze_task_achievement(question, graph_analysis, written_response)
#     ga_exercise = task1_generator.generate_grammar_exercises(ga, written_response)
#     lr_exercise = task1_generator.generate_vocabulary_exercises(lr)
#     return ga, lr, cc, ta, ga_exercise, lr_exercise


# def llm_responder_t2(question, written_response):
#     task2_evaluator = IELTSTask2Evaluator()
#     task2_generator = IELTSTask2ExerciseGenerator()
#     general_analysis = task2_evaluator.evaluate_essay(essay_question, essay_content)
#     ga =  task2_evaluator.analyze_grammar(written_response)
#     lr =  task2_evaluator.analyze_vocabulary(written_response)
#     ta =  task2_evaluator.analyze_task_achievement(essay_question, essay_content)
#     ga_exercise = task2_generator.generate_grammar_exercises(ga, essay_content)
#     lr_exercise = task2_generator.generate_vocabulary_exercises(lr)
    
#     return ga, lr, cc, ta, ga_exercise, lr_exercise

import os
import base64
from groq import Groq

# -------------------------------
# GLOBAL MODEL SETTINGS
# -------------------------------
TEXT_MODEL = "llama-3.1-70b-versatile"
FAST_MODEL = "llama3-8b-8192"
VISION_MODEL = "llama-3.2-11b-vision-preview"


# ================================================================
# ===============   TASK 2 EVALUATOR   ===========================
# ================================================================
class IELTSTask2Evaluator:
    def __init__(self):
        self.client = Groq(api_key=os.getenv("GROQ_API_KEY"))
        self.model = TEXT_MODEL

    # -------------------------------
    # SCORE ESSAY
    # -------------------------------
    def evaluate_essay(self, essay_question, essay_content):
        prompt = f"""
You are an IELTS examiner. Evaluate this Task 2 essay.

Strict rules:
- Score each criterion (TA, CC, LR, GRA) from **1 to 9**, only integers.
- Provide **3 examiner-style comments per criterion**.
- Base the evaluation strictly on IELTS Writing Task 2 band descriptors.

Essay Question: {essay_question}

Essay:
{essay_content}
"""
        return self._get_completion(prompt)

    # -------------------------------
    # GRAMMAR ANALYSIS
    # -------------------------------
    def analyze_grammar(self, essay_content):
        prompt = f"""
Provide a full grammar analysis for a B1–C1 learner.

Include:
- Grammar structures used
- Accuracy % (e.g., “Present Simple: 70%”)
- Explanations for inaccurate structures

Essay:
{essay_content}
"""
        return self._get_completion(prompt)

    # -------------------------------
    # VOCABULARY ANALYSIS
    # -------------------------------
    def analyze_vocabulary(self, essay_content):
        prompt = f"""
Provide a vocabulary analysis of the essay:

Include:
- Lexical errors + corrections
- Stronger alternatives for weak vocabulary
- Full sentence examples

Essay:
{essay_content}
"""
        return self._get_completion(prompt)

    # -------------------------------
    # COHESION & COHERENCE
    # -------------------------------
    def analyze_cohesion_coherence(self, essay_content):
        prompt = f"""
Evaluate cohesion & coherence (NO SCORES):

Criteria:
- Paraphrasing quality
- Logical sequencing
- Cohesive devices use
- Topic clarity per paragraph
- Paragraph structure quality

Essay:
{essay_content}
"""
        return self._get_completion(prompt)

    # -------------------------------
    # TASK ACHIEVEMENT
    # -------------------------------
    def analyze_task_achievement(self, essay_question, essay_content):
        prompt = f"""
Analyze Task Achievement for this Task 2 essay (NO SCORES):

Explain:
- Whether all parts of the question are addressed
- Idea development
- Position clarity
- Suggestions for improvement

Question: {essay_question}

Essay: {essay_content}
"""
        return self._get_completion(prompt)

    # -------------------------------
    # INTERNAL CALL
    # -------------------------------
    def _get_completion(self, prompt):
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message["content"]



# ================================================================
# ===============   TASK 2 EXERCISE GENERATOR   ==================
# ================================================================
class IELTSTask2ExerciseGenerator:
    def __init__(self):
        self.client = Groq(api_key=os.getenv("GROQ_API_KEY"))
        self.model = FAST_MODEL

    def generate_grammar_exercises(self, grammar_analysis, essay_content):
        prompt = f"""
Create grammar exercises based on this grammar analysis.

Rules:
- 4 exercise types
- 10 items each
- All exercises must use the essay’s topic
- Do NOT copy student mistakes

Grammar Analysis:
{grammar_analysis}

Essay:
{essay_content}
"""
        return self._get_completion(prompt)

    def generate_vocabulary_exercises(self, vocab_analysis):
        prompt = f"""
Create vocabulary practice exercises based on these lexical issues.

Include:
- Reformulation
- Synonyms
- Contextual rewriting

Vocabulary Analysis:
{vocab_analysis}
"""
        return self._get_completion(prompt)

    def _get_completion(self, prompt):
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        )
        return response.choices[0].message["content"]



# ================================================================
# ===============   TASK 1 EVALUATOR   ===========================
# ================================================================
class IELTSTask1Evaluator:
    def __init__(self):
        self.client = Groq(api_key=os.getenv("GROQ_API_KEY"))
        self.text_model = TEXT_MODEL
        self.vision_model = VISION_MODEL

    def encode_image(self, path):
        with open(path, "rb") as f:
            return base64.b64encode(f.read()).decode()

    # -------------------------------
    # GRAPH ANALYSIS (VISION)
    # -------------------------------
    def analyze_graph(self, image_path, question):
        base64_img = self.encode_image(image_path)

        response = self.client.chat.completions.create(
            model=self.vision_model,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text",
                         "text": f"Analyze this IELTS Task 1 graph. Question: {question}"},
                        {"type": "image_url",
                         "image_url": {"url": f"data:image/jpeg;base64,{base64_img}"}}
                    ]
                }
            ]
        )
        return response.choices[0].message["content"]

    # -------------------------------
    # TASK 1 FULL EVALUATION
    # -------------------------------
    def evaluate_task1_response(self, question, graph_analysis, written_response):
        prompt = f"""
Evaluate this IELTS Task 1 response.

Provide:
- Integer band scores (1–9) for TA, CC, LR, GRA
- 3 comments per criterion
- Compare student writing to the graph analysis

Question: {question}

Graph Analysis:
{graph_analysis}

Response:
{written_response}
"""
        return self._get_completion(prompt)

    # -------------------------------
    # OTHER ANALYSES (Grammar, Vocabulary, TA, CC)
    # -------------------------------
    def analyze_grammar(self, text):
        prompt = f"""
Analyze grammar for Task 1 response:

Focus:
- Tenses for trends
- Comparative structures
- Passive forms
- Prepositions for charts
- Numeric language

Response:
{text}
"""
        return self._get_completion(prompt)

    def analyze_vocabulary(self, text):
        prompt = f"""
Analyze vocabulary for Task 1:

Include:
- Trend vocabulary
- Comparison vocabulary
- Chart terminology
- Better synonyms

Response:
{text}
"""
        return self._get_completion(prompt)

    def analyze_task_achievement(self, question, graph_analysis, text):
        prompt = f"""
Evaluate Task Achievement (NO SCORES):

Compare:
- Key features vs graph analysis
- Overview quality
- Trend accuracy
- Detail selection

Question: {question}

Graph:
{graph_analysis}

Response:
{text}
"""
        return self._get_completion(prompt)

    def analyze_cohesion_coherence(self, text, graph_analysis):
        prompt = f"""
Evaluate Cohesion & Coherence (NO SCORES):

Graph Reference:
{graph_analysis}

Response:
{text}
"""
        return self._get_completion(prompt)

    def _get_completion(self, prompt):
        resp = self.client.chat.completions.create(
            model=self.text_model,
            messages=[{"role": "user", "content": prompt}]
        )
        return resp.choices[0].message["content"]



# ================================================================
# ===============   TASK 1 EXERCISE GENERATOR   ==================
# ================================================================
class IELTSTask1ExerciseGenerator:
    def __init__(self):
        self.client = Groq(api_key=os.getenv("GROQ_API_KEY"))
        self.model = FAST_MODEL

    def generate_grammar_exercises(self, grammar_analysis, essay_content):
        prompt = f"""
Generate Task 1 grammar exercises:
- 4 exercise types
- 10 items each
- Based on grammar analysis
- Context must match essay topic

Grammar Analysis:
{grammar_analysis}

Essay:
{essay_content}
"""
        return self._get_completion(prompt)

    def generate_graph_description_exercises(self, graph_analysis):
        prompt = f"""
Create Task 1 exercises:

1. Write an overview
2. Describe a trend
3. Compare two data points
4. Select key features

Graph Analysis:
{graph_analysis}
"""
        return self._get_completion(prompt)

    def generate_vocabulary_exercises(self, vocab_analysis):
        prompt = f"""
Create Task 1 vocabulary exercises:

Include:
- Trend verbs
- Comparison vocabulary
- Chart-specific words

Vocabulary Analysis:
{vocab_analysis}
"""
        return self._get_completion(prompt)

    def _get_completion(self, prompt):
        resp = self.client.chat.completions.create(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        )
        return resp.choices[0].message["content"]



# ================================================================
# ===============   T1 & T2 RESPONDER ============================
# ================================================================
def llm_responder_t1(image_path, question, written_response):
    ev = IELTSTask1Evaluator()
    ex = IELTSTask1ExerciseGenerator()

    graph = ev.analyze_graph(image_path, question)
    evaluation = ev.evaluate_task1_response(question, graph, written_response)
    grammar = ev.analyze_grammar(written_response)
    vocab = ev.analyze_vocabulary(written_response)
    cohesion = ev.analyze_cohesion_coherence(written_response, graph)
    task_ach = ev.analyze_task_achievement(question, graph, written_response)

    grammar_ex = ex.generate_grammar_exercises(grammar, written_response)
    vocab_ex = ex.generate_vocabulary_exercises(vocab)

    return evaluation, grammar, vocab, cohesion, task_ach, grammar_ex, vocab_ex


def llm_responder_t2(question, written_response):
    ev = IELTSTask2Evaluator()
    ex = IELTSTask2ExerciseGenerator()

    evaluation = ev.evaluate_essay(question, written_response)
    grammar = ev.analyze_grammar(written_response)
    vocab = ev.analyze_vocabulary(written_response)
    cohesion = ev.analyze_cohesion_coherence(written_response)
    task_ach = ev.analyze_task_achievement(question, written_response)

    grammar_ex = ex.generate_grammar_exercises(grammar, written_response)
    vocab_ex = ex.generate_vocabulary_exercises(vocab)

    return evaluation, grammar, vocab, cohesion, task_ach, grammar_ex, vocab_ex