Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -30,7 +30,7 @@ class QuizGenerator:
|
|
30 |
prompt = self._create_prompt(text, num_questions)
|
31 |
|
32 |
try:
|
33 |
-
# API call with simplified parameters
|
34 |
response = self.client.chat.completions.create(
|
35 |
messages=[
|
36 |
{
|
@@ -43,14 +43,11 @@ class QuizGenerator:
|
|
43 |
}
|
44 |
],
|
45 |
model="llama-3.2-3b-preview",
|
46 |
-
temperature=0.1,
|
47 |
max_tokens=1024
|
48 |
)
|
49 |
|
50 |
# Extract content safely
|
51 |
-
if not response or not hasattr(response.choices[0], 'message'):
|
52 |
-
raise ValueError("Invalid API response structure")
|
53 |
-
|
54 |
content = response.choices[0].message.content
|
55 |
if not content:
|
56 |
raise ValueError("Empty response content")
|
@@ -67,12 +64,12 @@ class QuizGenerator:
|
|
67 |
except Exception as e:
|
68 |
print(f"Error in generate_questions: {str(e)}")
|
69 |
if 'response' in locals():
|
70 |
-
print("Response content:",
|
71 |
raise QuizGenerationError(f"Failed to generate questions: {str(e)}")
|
72 |
|
73 |
def _create_prompt(self, text: str, num_questions: int) -> str:
|
74 |
"""Create a simple, clear prompt optimized for llama-3.2-3b-preview"""
|
75 |
-
return f"""Create {num_questions} multiple choice questions about this text.
|
76 |
[
|
77 |
{{
|
78 |
"question": "Write the question here?",
|
@@ -91,7 +88,6 @@ Rules:
|
|
91 |
2. Each question must have exactly 4 options
|
92 |
3. correct_answer must be 0, 1, 2, or 3
|
93 |
4. No explanations or additional text
|
94 |
-
5. Keep options short and clear
|
95 |
|
96 |
Text to use:
|
97 |
{text.strip()}"""
|
@@ -102,7 +98,7 @@ Text to use:
|
|
102 |
# Clean up the response text
|
103 |
cleaned = response_text.strip()
|
104 |
|
105 |
-
# Remove any markdown
|
106 |
cleaned = cleaned.replace('```json', '').replace('```', '').strip()
|
107 |
|
108 |
# Find the JSON array
|
@@ -114,27 +110,35 @@ Text to use:
|
|
114 |
|
115 |
json_str = cleaned[start:end]
|
116 |
|
117 |
-
#
|
118 |
-
|
119 |
-
|
120 |
|
|
|
121 |
try:
|
122 |
-
|
123 |
-
except json.JSONDecodeError
|
124 |
-
#
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
if not isinstance(questions, list):
|
130 |
-
raise ValueError("Parsed JSON is not a list")
|
131 |
-
|
132 |
-
return questions
|
133 |
-
|
134 |
except Exception as e:
|
135 |
print(f"Parse error details: {str(e)}")
|
136 |
print(f"Attempted to parse: {response_text}")
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
|
139 |
def _validate_questions(self, questions: List[Dict], num_questions: int) -> List[Question]:
|
140 |
"""Validate questions with strict checking"""
|
@@ -175,6 +179,13 @@ Text to use:
|
|
175 |
|
176 |
return validated
|
177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
class FontManager:
|
180 |
"""Manages font installation and loading for the certificate generator"""
|
|
|
30 |
prompt = self._create_prompt(text, num_questions)
|
31 |
|
32 |
try:
|
33 |
+
# API call with simplified parameters
|
34 |
response = self.client.chat.completions.create(
|
35 |
messages=[
|
36 |
{
|
|
|
43 |
}
|
44 |
],
|
45 |
model="llama-3.2-3b-preview",
|
46 |
+
temperature=0.1,
|
47 |
max_tokens=1024
|
48 |
)
|
49 |
|
50 |
# Extract content safely
|
|
|
|
|
|
|
51 |
content = response.choices[0].message.content
|
52 |
if not content:
|
53 |
raise ValueError("Empty response content")
|
|
|
64 |
except Exception as e:
|
65 |
print(f"Error in generate_questions: {str(e)}")
|
66 |
if 'response' in locals():
|
67 |
+
print("Response content:", content if 'content' in locals() else None)
|
68 |
raise QuizGenerationError(f"Failed to generate questions: {str(e)}")
|
69 |
|
70 |
def _create_prompt(self, text: str, num_questions: int) -> str:
|
71 |
"""Create a simple, clear prompt optimized for llama-3.2-3b-preview"""
|
72 |
+
return f"""Create {num_questions} multiple choice questions about this text. Return only the JSON array in this exact format:
|
73 |
[
|
74 |
{{
|
75 |
"question": "Write the question here?",
|
|
|
88 |
2. Each question must have exactly 4 options
|
89 |
3. correct_answer must be 0, 1, 2, or 3
|
90 |
4. No explanations or additional text
|
|
|
91 |
|
92 |
Text to use:
|
93 |
{text.strip()}"""
|
|
|
98 |
# Clean up the response text
|
99 |
cleaned = response_text.strip()
|
100 |
|
101 |
+
# Remove any markdown formatting
|
102 |
cleaned = cleaned.replace('```json', '').replace('```', '').strip()
|
103 |
|
104 |
# Find the JSON array
|
|
|
110 |
|
111 |
json_str = cleaned[start:end]
|
112 |
|
113 |
+
# Remove any trailing commas before closing brackets
|
114 |
+
json_str = re.sub(r',(\s*})', r'\1', json_str)
|
115 |
+
json_str = re.sub(r',(\s*])', r'\1', json_str)
|
116 |
|
117 |
+
# Try to parse the cleaned JSON
|
118 |
try:
|
119 |
+
return json.loads(json_str)
|
120 |
+
except json.JSONDecodeError:
|
121 |
+
# If that fails, try using ast.literal_eval as a fallback
|
122 |
+
import ast
|
123 |
+
return ast.literal_eval(json_str)
|
124 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
except Exception as e:
|
126 |
print(f"Parse error details: {str(e)}")
|
127 |
print(f"Attempted to parse: {response_text}")
|
128 |
+
|
129 |
+
# Last resort: try to fix the JSON manually
|
130 |
+
try:
|
131 |
+
# Remove any trailing commas and fix newlines
|
132 |
+
fixed = re.sub(r',(\s*[}\]])', r'\1', response_text)
|
133 |
+
fixed = fixed.replace('}\n{', '},{')
|
134 |
+
fixed = fixed.strip()
|
135 |
+
if not fixed.startswith('['):
|
136 |
+
fixed = '[' + fixed
|
137 |
+
if not fixed.endswith(']'):
|
138 |
+
fixed = fixed + ']'
|
139 |
+
return json.loads(fixed)
|
140 |
+
except:
|
141 |
+
raise ValueError(f"Failed to parse response: {str(e)}")
|
142 |
|
143 |
def _validate_questions(self, questions: List[Dict], num_questions: int) -> List[Question]:
|
144 |
"""Validate questions with strict checking"""
|
|
|
179 |
|
180 |
return validated
|
181 |
|
182 |
+
def _is_valid_json(self, json_str: str) -> bool:
|
183 |
+
"""Check if a string is valid JSON"""
|
184 |
+
try:
|
185 |
+
json.loads(json_str)
|
186 |
+
return True
|
187 |
+
except:
|
188 |
+
return False
|
189 |
|
190 |
class FontManager:
|
191 |
"""Manages font installation and loading for the certificate generator"""
|