samspeaks5 commited on
Commit
8cbac82
·
verified ·
1 Parent(s): f93dc73

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +3 -0
  2. app.py +66 -20
README.md CHANGED
@@ -24,6 +24,9 @@ AnkiGen is a Gradio-based web application that generates Anki-compatible CSV fil
24
 
25
  - instead of Openai, Openrouter is added as an free alternative :)
26
 
 
 
 
27
 
28
  ## Screenshot
29
 
 
24
 
25
  - instead of Openai, Openrouter is added as an free alternative :)
26
 
27
+ ## Issues
28
+ - Some times Mistal 7B returns <unk> tokens.
29
+ - Rate limit of Gemini models
30
 
31
  ## Screenshot
32
 
app.py CHANGED
@@ -3,6 +3,7 @@ from pydantic import BaseModel
3
  from typing import List, Optional
4
  import gradio as gr
5
  import json
 
6
 
7
 
8
 
@@ -39,7 +40,42 @@ class CardList(BaseModel):
39
  topic: str
40
  cards: List[Card]
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
43
  def structured_output_completion(
44
  client, model, system_prompt, user_prompt
45
  ):
@@ -55,13 +91,7 @@ def structured_output_completion(
55
  print("Raw API response:", completion)
56
 
57
  response_content = completion.choices[0].message.content
58
-
59
- try:
60
- parsed_response = json.loads(response_content)
61
- return parsed_response
62
- except json.JSONDecodeError:
63
- print("Invalid JSON response:", response_content)
64
- return None
65
 
66
  except Exception as e:
67
  print(f"An error occurred during the API call: {e}")
@@ -97,31 +127,45 @@ def generate_cards(
97
 
98
  topic_prompt = f"""
99
  Generate the top {topic_number} important subjects to know on {subject} in
100
- order of ascending difficulty. Return the result as a JSON array of objects,
101
- each containing 'subject' and 'difficulty' keys.
 
 
 
 
102
  """
103
  try:
104
  topics_response = structured_output_completion(
105
- client, model, system_prompt, topic_prompt
106
  )
107
  if topics_response is None:
108
  raise gr.Error("Failed to generate topics. Please try again.")
109
 
110
- topic_list = [item["subject"] for item in topics_response[:topic_number]]
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  except Exception as e:
113
  raise gr.Error(f"An error occurred: {str(e)}. Please try again or check your API key.")
114
 
115
  for topic in topic_list:
116
  card_prompt = f"""
117
- Generate {cards_per_topic} cards on {subject}: "{topic}"
118
  keeping in mind the user's preferences: {preference_prompt}.
119
-
120
  Questions should cover both sample problems and concepts.
121
-
122
- Use the explanation field to help the user understand the reason behind things
123
  and maximize learning. Additionally, offer tips (performance, gotchas, etc.).
124
-
125
  Return the result as a JSON object with the following structure:
126
  {{
127
  "topic": "string",
@@ -140,15 +184,17 @@ def generate_cards(
140
 
141
  try:
142
  cards = structured_output_completion(
143
- client, model, system_prompt, card_prompt
144
  )
145
  if cards is None:
146
  print(f"Failed to generate cards for topic '{topic}'.")
147
  continue
148
- if not isinstance(cards, dict) or 'topic' not in cards or 'cards' not in cards:
 
 
 
 
149
  print(f"Invalid card response format for topic '{topic}'.")
150
- continue
151
- all_card_lists.append(cards)
152
  except Exception as e:
153
  print(f"An error occurred while generating cards for topic '{topic}': {e}")
154
  continue
 
3
  from typing import List, Optional
4
  import gradio as gr
5
  import json
6
+ import re
7
 
8
 
9
 
 
40
  topic: str
41
  cards: List[Card]
42
 
43
+ def universal_response_handler(response_content):
44
+ # Extract JSON content from the response
45
+ json_match = re.search(r'\{.*\}|\[.*\]', response_content, re.DOTALL)
46
+ if json_match:
47
+ json_content = json_match.group()
48
+ else:
49
+ print("No JSON content found in the response")
50
+ return None
51
+
52
+ try:
53
+ # Parse the JSON content
54
+ parsed_response = json.loads(json_content)
55
+
56
+ # If the parsed response is a list, return it directly
57
+ if isinstance(parsed_response, list):
58
+ return parsed_response
59
+ # If it's a dict, check if it has a 'result' key
60
+ elif isinstance(parsed_response, dict):
61
+ if 'result' in parsed_response:
62
+ return parsed_response['result']
63
+ elif 'topic' in parsed_response and 'cards' in parsed_response:
64
+ # Handle the case where we get a single topic with cards
65
+ return [parsed_response]
66
+ else:
67
+ return [parsed_response]
68
+ else:
69
+ print("Unexpected response format:", parsed_response)
70
+ return None
71
 
72
+ except json.JSONDecodeError:
73
+ print("Invalid JSON response:", json_content)
74
+ return None
75
+ except Exception as ex:
76
+ print(f"An error occurred while parsing the response: {ex}")
77
+ return None
78
+
79
  def structured_output_completion(
80
  client, model, system_prompt, user_prompt
81
  ):
 
91
  print("Raw API response:", completion)
92
 
93
  response_content = completion.choices[0].message.content
94
+ return universal_response_handler(response_content)
 
 
 
 
 
 
95
 
96
  except Exception as e:
97
  print(f"An error occurred during the API call: {e}")
 
127
 
128
  topic_prompt = f"""
129
  Generate the top {topic_number} important subjects to know on {subject} in
130
+ order of ascending difficulty. Return ONLY a JSON array of objects,
131
+ each containing 'subject' and 'difficulty' keys. Do not include any additional text or explanations. For example:
132
+ [
133
+ {{"subject": "Basic Concept 1", "difficulty": 1}},
134
+ {{"subject": "Advanced Concept 2", "difficulty": 2}}
135
+ ]
136
  """
137
  try:
138
  topics_response = structured_output_completion(
139
+ client, model_name, system_prompt, topic_prompt
140
  )
141
  if topics_response is None:
142
  raise gr.Error("Failed to generate topics. Please try again.")
143
 
144
+ if isinstance(topics_response, list):
145
+ topic_list = []
146
+ for item in topics_response[:topic_number]:
147
+ if isinstance(item, dict):
148
+ topic = item.get('subject') or item.get('topic')
149
+ if topic:
150
+ topic_list.append(topic)
151
+ elif isinstance(item, str):
152
+ topic_list.append(item)
153
+
154
+ if not topic_list:
155
+ raise gr.Error("Unexpected response format. Please try again.")
156
+ else:
157
+ raise gr.Error("Unexpected response format. Please try again.")
158
 
159
  except Exception as e:
160
  raise gr.Error(f"An error occurred: {str(e)}. Please try again or check your API key.")
161
 
162
  for topic in topic_list:
163
  card_prompt = f"""
164
+ Generate {cards_per_topic} cards on {subject}: "{topic}"
165
  keeping in mind the user's preferences: {preference_prompt}.
 
166
  Questions should cover both sample problems and concepts.
167
+ Use the explanation field to help the user understand the reason behind things
 
168
  and maximize learning. Additionally, offer tips (performance, gotchas, etc.).
 
169
  Return the result as a JSON object with the following structure:
170
  {{
171
  "topic": "string",
 
184
 
185
  try:
186
  cards = structured_output_completion(
187
+ client, model_name, system_prompt, card_prompt
188
  )
189
  if cards is None:
190
  print(f"Failed to generate cards for topic '{topic}'.")
191
  continue
192
+ if isinstance(cards, dict) and 'topic' in cards and 'cards' in cards:
193
+ all_card_lists.append(cards)
194
+ elif isinstance(cards, list) and len(cards) > 0 and isinstance(cards[0], dict) and 'topic' in cards[0] and 'cards' in cards[0]:
195
+ all_card_lists.extend(cards)
196
+ else:
197
  print(f"Invalid card response format for topic '{topic}'.")
 
 
198
  except Exception as e:
199
  print(f"An error occurred while generating cards for topic '{topic}': {e}")
200
  continue