ReneeHWT commited on
Commit
e179409
·
verified ·
1 Parent(s): 4567f58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -127
app.py CHANGED
@@ -1,133 +1,152 @@
1
  import gradio as gr
2
  import random
3
- import pandas as pd
4
- import ssl
5
- import os
6
- from datetime import datetime
7
- import requests
8
-
9
- # Workaround for SSL issues in some environments
10
- ssl._create_default_https_context = ssl._create_unverified_context
11
-
12
- # Global Variables
13
- vocabulary = []
14
- matches = {}
15
- score = 0
16
- remaining_pairs = 0
17
- selected_pairs = []
18
-
19
- # Helper Functions for Matching Game
20
- def parse_csv(file):
21
- global remaining_pairs
22
- try:
23
- data = pd.read_csv(file.name, header=None)
24
- vocab = data.dropna().values.tolist()
25
- vocabulary.clear()
26
- vocabulary.extend([{"word": row[0].strip(), "definition": row[1].strip()} for row in vocab])
27
- remaining_pairs = len(vocabulary)
28
- return f"Uploaded successfully! {remaining_pairs} pairs added.", vocabulary
29
- except Exception as e:
30
- return "Error reading the file. Ensure it's a valid CSV.", vocabulary
31
-
32
- def start_game():
33
- global matches, score, remaining_pairs, selected_pairs
34
- if len(vocabulary) < 1:
35
- return "Please upload a vocabulary file or add words first.", [], []
36
-
37
- score = 0
38
- remaining_pairs = len(vocabulary)
39
  random.shuffle(vocabulary)
40
- words = [item['word'] for item in vocabulary]
41
- definitions = [item['definition'] for item in vocabulary]
42
- random.shuffle(definitions)
 
43
 
44
- matches = {item['word']: item['definition'] for item in vocabulary}
45
- selected_pairs = [] # Reset selected pairs
 
 
 
 
 
 
 
 
 
46
 
47
- word_cards = [{'label': w, 'value': w} for w in words]
48
- definition_cards = [{'label': d, 'value': d} for d in definitions]
49
-
50
- return "Match words with their definitions to eliminate pairs.", word_cards, definition_cards
51
-
52
- def check_match(word, definition):
53
- global matches, score, remaining_pairs, vocabulary, selected_pairs
54
- if matches.get(word) == definition:
55
- score += 1
56
- remaining_pairs -= 1
57
- # Mark the matched pair as selected
58
- selected_pairs.append((word, definition))
59
-
60
- # Remove the matched pair from the game
61
- vocabulary = [item for item in vocabulary if item['word'] != word]
62
- if remaining_pairs == 0:
63
- return "Correct! You've matched all pairs! 🎉 Game Over.", score, [], []
64
-
65
- # Update words and definitions for remaining pairs
66
- words = [{'label': item['word'], 'value': item['word']} for item in vocabulary]
67
- definitions = [{'label': item['definition'], 'value': item['definition']} for item in vocabulary]
68
-
69
- return f"Correct! {word} matches {definition}. Remaining pairs: {remaining_pairs}", score, words, definitions
70
  else:
71
- return f"Incorrect! {word} does not match {definition}. Try again.", score, [], []
72
-
73
- def reset_game():
74
- global vocabulary, matches, score, remaining_pairs, selected_pairs
75
- vocabulary.clear()
76
- matches.clear()
77
- score = 0
78
- remaining_pairs = 0
79
- selected_pairs.clear()
80
- return "Game reset. Upload a new file or add words to start again.", vocabulary
81
-
82
- # Gradio Interface
83
- def main():
84
- with gr.Blocks() as app:
85
- gr.Markdown("# Vocabulary Matching Game")
86
-
87
- with gr.Tab("Upload Vocabulary"):
88
- csv_upload = gr.File(label="Upload CSV (word, definition)")
89
- upload_button = gr.Button("Upload File")
90
- upload_output = gr.Textbox(label="Upload Status")
91
-
92
- with gr.Tab("Play Matching Game"):
93
- game_status = gr.Textbox(label="Game Status")
94
- start_button = gr.Button("Start Game")
95
- word_cards = gr.Gallery(label="Word Cards", height=300)
96
- definition_cards = gr.Gallery(label="Definition Cards", height=300)
97
-
98
- selected_word = gr.Textbox(label="Selected Word", interactive=False)
99
- selected_definition = gr.Textbox(label="Selected Definition", interactive=False)
100
-
101
- match_button = gr.Button("Check Match")
102
- match_output = gr.Textbox(label="Match Result")
103
- score_output = gr.Textbox(label="Score")
104
- remaining_output = gr.Textbox(label="Remaining Pairs")
105
-
106
- def select_word(word):
107
- return word
108
-
109
- def select_definition(definition):
110
- return definition
111
-
112
- word_cards.select(select_word, inputs=[], outputs=[selected_word])
113
- definition_cards.select(select_definition, inputs=[], outputs=[selected_definition])
114
-
115
- match_button.click(
116
- check_match,
117
- inputs=[selected_word, selected_definition],
118
- outputs=[match_output, score_output, word_cards, definition_cards]
119
- )
120
-
121
- with gr.Tab("Reset Game"):
122
- reset_button = gr.Button("Reset")
123
- reset_output = gr.Textbox(label="Reset Status")
124
-
125
- upload_button.click(parse_csv, inputs=[csv_upload], outputs=[upload_output])
126
- start_button.click(start_game, outputs=[game_status, word_cards, definition_cards])
127
- reset_button.click(reset_game, outputs=[reset_output])
128
-
129
- return app
130
-
131
- if __name__ == "__main__":
132
- app = main()
133
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import random
3
+ import csv
4
+ import io
5
+
6
+ # Global states (to be stored in Gradio states)
7
+ # vocabulary: list of dicts [{'word': '...', 'definition': '...'}, ...]
8
+ # matched: number of correct matches made
9
+ # available_words: list of words currently un-matched
10
+ # available_definitions: list of definitions currently un-matched
11
+
12
+ def parse_csv(file, vocabulary):
13
+ if file is None:
14
+ return vocabulary
15
+ file_content = file.read().decode('utf-8').strip()
16
+ reader = csv.reader(io.StringIO(file_content))
17
+ for row in reader:
18
+ if len(row) >= 2:
19
+ word = row[0].strip()
20
+ definition = ",".join(row[1:]).strip()
21
+ if word and definition:
22
+ vocabulary.append({"word": word, "definition": definition})
23
+ return vocabulary
24
+
25
+ def add_manual_word(vocabulary, word, definition):
26
+ word = word.strip()
27
+ definition = definition.strip()
28
+ if word and definition:
29
+ vocabulary.append({"word": word, "definition": definition})
30
+ return vocabulary, f'Added "{word}" to your vocabulary.' if word and definition else "Please enter both a word and a definition."
31
+
32
+ def start_quiz(vocabulary):
33
+ if not vocabulary:
34
+ return gr.update(visible=False), "No vocabulary available. Please upload CSV or add words.", None, None, None, None
35
+ # Shuffle the vocabulary for a quiz
 
 
 
36
  random.shuffle(vocabulary)
37
+ words = [v["word"] for v in vocabulary]
38
+ defs = [v["definition"] for v in vocabulary]
39
+ random.shuffle(defs)
40
+ return gr.update(visible=True), "Quiz started! Match words with definitions.", vocabulary, words, defs, 0
41
 
42
+ def check_match(selected_word, selected_def, vocabulary, words, defs, matched):
43
+ if not selected_word or not selected_def:
44
+ return "Please select both a word and a definition.", words, defs, matched
45
+ # Find the correct definition for the selected word
46
+ correct_def = None
47
+ for v in vocabulary:
48
+ if v["word"] == selected_word:
49
+ correct_def = v["definition"]
50
+ break
51
+ if correct_def is None:
52
+ return "Error: Word not found in vocabulary.", words, defs, matched
53
 
54
+ if correct_def == selected_def:
55
+ # Correct match
56
+ matched += 1
57
+ # Remove matched word and definition
58
+ words = [w for w in words if w != selected_word]
59
+ defs = [d for d in defs if d != selected_def]
60
+ if matched == len(vocabulary):
61
+ return f"Correct! All {matched} matches completed!", words, defs, matched
62
+ else:
63
+ return f"Correct! {matched}/{len(vocabulary)} matched.", words, defs, matched
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  else:
65
+ return f"Incorrect! '{selected_word}' does not match the selected definition.", words, defs, matched
66
+
67
+ def reset_quiz():
68
+ return gr.update(visible=False), None, [], [], [], 0, None
69
+
70
+ with gr.Blocks() as demo:
71
+ gr.Markdown("# 📚 Personal English Vocabulary App")
72
+
73
+ vocabulary_state = gr.State([])
74
+ words_state = gr.State([])
75
+ defs_state = gr.State([])
76
+ matched_state = gr.State(0)
77
+
78
+ with gr.Box():
79
+ gr.Markdown("## Upload Your Vocabulary (CSV format: word, definition)")
80
+ file_input = gr.File(label="Upload CSV")
81
+ upload_btn = gr.Button("Parse CSV")
82
+ status_text = gr.Markdown("")
83
+
84
+ with gr.Box():
85
+ gr.Markdown("## Add a Vocabulary Word Manually")
86
+ manual_word = gr.Textbox(label="Word:")
87
+ manual_def = gr.Textbox(label="Definition:")
88
+ add_word_btn = gr.Button("Add Word")
89
+ add_status = gr.Markdown("")
90
+
91
+ start_quiz_btn = gr.Button("Start Quiz")
92
+
93
+ quiz_section = gr.Group(visible=False)
94
+ with quiz_section:
95
+ quiz_status = gr.Markdown("")
96
+ with gr.Row():
97
+ selected_word = gr.Dropdown(label="Words")
98
+ selected_def = gr.Dropdown(label="Definitions")
99
+ match_btn = gr.Button("Check Match")
100
+ match_result = gr.Markdown("")
101
+ reset_btn = gr.Button("Reset Quiz")
102
+
103
+ # Button actions
104
+ upload_btn.click(
105
+ parse_csv,
106
+ inputs=[file_input, vocabulary_state],
107
+ outputs=[vocabulary_state]
108
+ ).then(
109
+ lambda v: f"{len(v)} words loaded." if v else "No words loaded.",
110
+ inputs=[vocabulary_state],
111
+ outputs=status_text
112
+ )
113
+
114
+ add_word_btn.click(
115
+ add_manual_word,
116
+ inputs=[vocabulary_state, manual_word, manual_def],
117
+ outputs=[vocabulary_state, add_status]
118
+ )
119
+
120
+ start_quiz_btn.click(
121
+ start_quiz,
122
+ inputs=[vocabulary_state],
123
+ outputs=[quiz_section, quiz_status, vocabulary_state, words_state, defs_state, matched_state]
124
+ ).then(
125
+ lambda words, defs: (gr.update(choices=words, value=None), gr.update(choices=defs, value=None)),
126
+ inputs=[words_state, defs_state],
127
+ outputs=[selected_word, selected_def]
128
+ )
129
+
130
+ match_btn.click(
131
+ check_match,
132
+ inputs=[selected_word, selected_def, vocabulary_state, words_state, defs_state, matched_state],
133
+ outputs=[match_result, words_state, defs_state, matched_state]
134
+ ).then(
135
+ lambda words, defs: (gr.update(choices=words, value=None), gr.update(choices=defs, value=None)),
136
+ inputs=[words_state, defs_state],
137
+ outputs=[selected_word, selected_def]
138
+ )
139
+
140
+ reset_btn.click(
141
+ reset_quiz,
142
+ inputs=[],
143
+ outputs=[quiz_section, quiz_status, vocabulary_state, words_state, defs_state, matched_state, match_result]
144
+ ).then(
145
+ lambda: "",
146
+ outputs=add_status
147
+ ).then(
148
+ lambda: "",
149
+ outputs=status_text
150
+ )
151
+
152
+ demo.launch()