-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
289 lines (236 loc) · 10.8 KB
/
Copy pathreport.py
File metadata and controls
289 lines (236 loc) · 10.8 KB
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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import os
import datetime
import matplotlib.pyplot as plt
from docx import Document
from docx.shared import Inches
from docx.shared import RGBColor
import google.generativeai as genai
import json
import pandas as pd
def generate_radar_chart(correct_rates, output_path):
categories = list(correct_rates.keys())
values = list(correct_rates.values())
# Complete the radar chart by closing the loop
values += values[:1]
categories += categories[:1]
angles = [n / float(len(categories) - 1) * 2 * 3.14159 for n in range(len(categories))]
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={"polar": True})
ax.fill(angles, values, color="blue", alpha=0.25)
ax.plot(angles, values, color="blue", linewidth=2)
ax.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
ax.set_yticklabels(["20%", "40%", "60%", "80%", "100%"], color="grey", size=10)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories[:-1], size=10)
plt.savefig(output_path)
plt.close()
def get_gemini_feedback(score, correct_rates):
model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat()
report_example = """**Passage:**
TOEFL Practice Report
Summary
Score: 28
Performance Summary:
## TOEFL Performance Summary & Learning Suggestions
**Performance Summary:**
- **Strengths:** Demonstrated strong performance in identifying speaker implications, as seen in correctly answering "What does the speaker imply?" with Option C.
- **Areas for Improvement:** Main idea questions were a challenge, as illustrated by selecting Option B instead of the correct Option A. The misunderstanding likely stemmed from not fully grasping the passage's primary focus.
**Future Learning Suggestions:**
1. **Enhance Main Idea Identification Skills:**
- Focus on summarizing passages in your own words after reading or listening.
- Practice identifying topic sentences and distinguishing main ideas from supporting details.
- Utilize TOEFL preparation resources that emphasize comprehension of main ideas.
2. **Improve Reading Strategies:**
- Skim passages to get a sense of structure before reading in detail.
- Pay attention to transitional phrases that indicate the author’s intent or key points.
3. **Regular Practice:**
- Use practice questions that mimic TOEFL formats to become more familiar with question phrasing.
- Review explanations for both correct and incorrect answers to deepen understanding.
"""
# 合併提示到單一請求中
if correct_rates!=-1:
prompt = (
f"Please generate a TOEFL performance report based on the example format below:\n\n{report_example}\n\n"
f"Score: {score}. Correct rates by question type: {correct_rates}.\n"
"Provide a performance summary and actionable advice."
)
elif correct_rates==-1:
prompt = (
f"Please generate a TOEFL performance report based on the example format below:\n\n{report_example}\n\n"
f"Score: {score}.\n"
"Provide a performance summary and actionable advice."
)
try:
response = chat.send_message(prompt)
if response.text:
# 使用更靈活的解析邏輯
summary_start = response.text.find("Summary:")
suggestions_start = response.text.find("Suggestions:")
summary = (
response.text[summary_start:suggestions_start].strip()
if summary_start != -1 and suggestions_start != -1
else "No summary available."
)
suggestions = (
response.text[suggestions_start:].strip()
if suggestions_start != -1
else "No suggestions available."
)
return {"summary": summary, "suggestions": suggestions}
else:
raise ValueError("No response text from model.")
except Exception as e:
return {"summary": "Error generating summary.", "suggestions": f"Error: {str(e)}"}
def listening_report(l_df_get, user_ans):
def check_listening(l_df_get, user_ans):
l_df_get = pd.read_csv("listening.csv")
for key, value in user_ans.items():
l_df_get.loc[l_df_get["number"] == int(key), 'user_ans'] = value
l_df_get["correct"] = (l_df_get["answer"] == l_df_get["user_ans"]).astype(int)
score = (l_df_get["correct"].sum())/11*30
type_scores = l_df_get.groupby("question_type")["correct"].mean().to_dict()
l_score_get = {"score" : score , "type_scores" : type_scores}
return [l_df_get,l_score_get]
check=check_listening(l_df_get, user_ans)
data=check[1]
df=check[0]
radar_chart_path = "radar_chart.png"
generate_radar_chart(data["type_scores"], radar_chart_path)
feedback = get_gemini_feedback(data["score"], data["type_scores"])
# Step 4: Create DOCX File
def create_docx(data, feedback, radar_chart_path):
doc = Document()
doc.add_heading("TOEFL Listening Practice Report", level=1)
# Add Summary
doc.add_heading("Summary", level=2)
doc.add_paragraph(f"Score: {data['score']}")
doc.add_picture(radar_chart_path, width=Inches(4))
doc.add_paragraph("Performance Summary:")
doc.add_paragraph(feedback.get("summary", "No summary available."))
doc.add_paragraph("Future Learning Suggestions:")
doc.add_paragraph(feedback.get("suggestions", "No suggestions available."))
# Add Question Details
# Iterate through the data and add to the document
for index, row in df.iterrows():
doc.add_paragraph(f"Number: {row['number']}")
doc.add_paragraph(f"Speech: {row['speech']}")
doc.add_paragraph(f"Question: {row['question']}")
doc.add_paragraph(f"Option A: {row['A']}")
doc.add_paragraph(f"Option B: {row['B']}")
doc.add_paragraph(f"Option C: {row['C']}")
doc.add_paragraph(f"Option D: {row['D']}")
doc.add_paragraph(f"Correct Answer: {row['answer']}")
doc.add_paragraph(f"Question Type: {row['question_type']}")
doc.add_paragraph("---")
# Save the Document()
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M")
file_name = f"TOEFL_Listening_Report_{timestamp}.docx"
doc.save(file_name)
return file_name
docx_file = create_docx(data, feedback, radar_chart_path)
print(f"Report generated: {docx_file}")
def reading_report(r_df_get, user_ans):
def check_reading(r_df_get, user_ans):
for key, value in user_ans.items():
r_df_get.loc[r_df_get["number"] == int(key), 'user_ans'] = value
r_df_get["correct"] = (r_df_get["Ans"] == r_df_get["user_ans"]).astype(int)
r_score = (r_df_get["correct"].sum())
return [r_df_get,r_score]
check=check_reading(r_df_get, user_ans)
data=check[1]
df=check[0]
feedback = get_gemini_feedback(data, -1)
# Step 4: Create DOCX File
def create_docx(data, feedback):
doc = Document()
doc.add_heading("TOEFL Reading Practice Report", level=1)
# Add Summary
doc.add_heading("Summary", level=2)
doc.add_paragraph(f"Score: {data}")
doc.add_paragraph("Performance Summary:")
doc.add_paragraph(feedback.get("summary", "No summary available."))
doc.add_paragraph("Future Learning Suggestions:")
doc.add_paragraph(feedback.get("suggestions", "No suggestions available."))
# Add Question Details
# Iterate through the data and add to the document
for index, row in df.iterrows():
doc.add_paragraph(f"Number: {row['number']}")
doc.add_paragraph(f"Article: {row['Article']}")
doc.add_paragraph(f"Question: {row['Question']}")
doc.add_paragraph(f"Option A: {row['A']}")
doc.add_paragraph(f"Option B: {row['B']}")
doc.add_paragraph(f"Option C: {row['C']}")
doc.add_paragraph(f"Option D: {row['D']}")
doc.add_paragraph(f"Correct Answer: {row['Ans']}")
# Save the Document()
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M")
file_name = f"TOEFL_Reading_Report_{timestamp}.docx"
doc.save(file_name)
return file_name
docx_file = create_docx(data, feedback)
print(f"Report generated: {docx_file}")
def speaking_report(s_list_get):
# Create a new Word document
doc = Document()
# Add the title
doc.add_heading("TOEFL Speaking Practice Report", level=1)
# Get and display the score
score = s_score_get()
doc.add_heading("Score", level=2)
doc.add_paragraph(f"Your Score: {score}")
# Get and display the comment
comment = s_com_get()
doc.add_heading("Comments", level=2)
doc.add_paragraph(comment)
# Get the questions and answers
questions = s_q_list_get()
answers = s_ans_list_get()
doc.add_heading("Question Details", level=2)
# Add each question and its corresponding answer
for i, question in enumerate(questions):
q_paragraph = doc.add_paragraph()
q_paragraph.add_run(f"Question {i + 1}: ").bold = True
q_paragraph.add_run(question)
a_paragraph = doc.add_paragraph()
a_paragraph.add_run("Reponses: ").bold = True
user_response = answers[i]
a_paragraph.add_run(user_response)
# Save the Word document
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M")
file_name = f"TOEFL_Speaking_Report_{timestamp}.docx"
doc.save(file_name)
print(f"Report saved to {file_name}")
def writing_report():
# Create a new Word document
doc = Document()
# Add the title
doc.add_heading("TOEFL Writing Practice Report", level=1)
# Get and display the score
score = w_score_get()
doc.add_heading("Score", level=2)
doc.add_paragraph(f"Your Score: {score}")
# Get and display the comment
comment = w_com_get()
doc.add_heading("Comments", level=2)
doc.add_paragraph(comment)
# Get the questions and answers
questions = w_q_list_get()
answers = w_ans_list_get()
doc.add_heading("Question Details", level=2)
# Add each question and its corresponding answer
for i, question in enumerate(questions):
q_paragraph = doc.add_paragraph()
q_paragraph.add_run(f"Question {i + 1}: ").bold = True
q_paragraph.add_run(question)
a_paragraph = doc.add_paragraph()
a_paragraph.add_run("Reponses: ").bold = True
user_response = answers[i]
a_paragraph.add_run(user_response)
# Save the Word document
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M")
file_name = f"TOEFL_Writing_Report_{timestamp}.docx"
doc.save(file_name)
print(f"Report saved to {file_name}")