hansaka1 commited on
Commit
c5bcf4c
Β·
verified Β·
1 Parent(s): 178832d

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +233 -0
main.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import re
3
+ from collections import defaultdict
4
+
5
+ # --- Core Wordle Solver Logic (from the console app) ---
6
+
7
+ def load_words():
8
+ """Load 5-letter words from the words.txt file."""
9
+ words = []
10
+ try:
11
+ with open('words.txt', 'r') as f:
12
+ for line in f:
13
+ word = line.strip().lower()
14
+ if len(word) == 5 and word.isalpha():
15
+ words.append(word)
16
+ except FileNotFoundError:
17
+ print("FATAL ERROR: words.txt not found. Please create it in the same directory.")
18
+ return None
19
+ return words
20
+
21
+ WORD_LIST = load_words()
22
+
23
+ def word_matches_clue(word, guess_word, emoji_result):
24
+ """Check if a word is consistent with a single guess clue."""
25
+ # Green check: letters must match at the exact position
26
+ for i, (guess_char, emoji) in enumerate(zip(guess_word, emoji_result)):
27
+ if emoji == '🟩' and word[i] != guess_char:
28
+ return False
29
+
30
+ # Yellow check: letter must be in the word but not at this position
31
+ for i, (guess_char, emoji) in enumerate(zip(guess_word, emoji_result)):
32
+ if emoji == '🟨':
33
+ if guess_char not in word or word[i] == guess_char:
34
+ return False
35
+
36
+ # Red/Black check: letter should not be in the word, unless it was also a green/yellow
37
+ # This handles duplicate letters correctly.
38
+ for i, (guess_char, emoji) in enumerate(zip(guess_word, emoji_result)):
39
+ if emoji in ['πŸŸ₯', '⬛']:
40
+ # Count occurrences of the letter in the guess and the word
41
+ guess_char_count_in_clues = sum(1 for j, g_char in enumerate(guess_word) if g_char == guess_char and emoji_result[j] in ['🟩', '🟨'])
42
+ word_char_count = word.count(guess_char)
43
+ if word_char_count > guess_char_count_in_clues:
44
+ return False
45
+
46
+ return True
47
+
48
+ def filter_words_by_clues(words, clues):
49
+ """Filter the main word list based on all collected clues."""
50
+ if not clues:
51
+ return words
52
+
53
+ remaining_words = list(words)
54
+ for guess_word, emoji_result in clues:
55
+ remaining_words = [word for word in remaining_words if word_matches_clue(word, guess_word, emoji_result)]
56
+
57
+ return remaining_words
58
+
59
+ def get_letter_frequency(words):
60
+ """Calculate the frequency of each letter in the remaining possible words."""
61
+ freq = defaultdict(int)
62
+ for word in words:
63
+ for char in set(word): # Count each letter only once per word
64
+ freq[char] += 1
65
+ return freq
66
+
67
+ def score_word(word, letter_freq):
68
+ """Score a word based on the frequency of its unique letters."""
69
+ score = 0
70
+ used_letters = set()
71
+ for char in word:
72
+ if char not in used_letters:
73
+ score += letter_freq[char]
74
+ used_letters.add(char)
75
+ return score
76
+
77
+ def get_best_guess(words, all_words):
78
+ """Determine the best next guess to narrow down possibilities."""
79
+ if not words:
80
+ return None, "No words match the clues."
81
+
82
+ if len(words) <= 2:
83
+ return words[0], f"{len(words)} possible words remain."
84
+
85
+ letter_freq = get_letter_frequency(words)
86
+
87
+ # We check from the entire word list to find a word that might reveal more information
88
+ # even if it's not in the list of possibilities. 'salet' is a great opener for this reason.
89
+ best_word = max(all_words, key=lambda w: score_word(w, letter_freq))
90
+
91
+ return best_word, f"{len(words)} possible words remain."
92
+
93
+
94
+ # --- Gradio Interface Functions ---
95
+
96
+ def process_guess(word, emojis, current_clues_list):
97
+ """
98
+ Handles the 'Submit Guess' button click.
99
+ Validates input, updates state, filters words, and returns new UI values.
100
+ """
101
+ # 1. Validation
102
+ if not word or not emojis:
103
+ error = "Please enter both a word and the emoji results."
104
+ return current_clues_list, gr.update(visible=True, value=error), "", "", format_clues_history(current_clues_list)
105
+
106
+ word = word.strip().lower()
107
+ emojis = emojis.strip()
108
+
109
+ if len(word) != 5 or not word.isalpha():
110
+ error = "Please enter a valid 5-letter word."
111
+ return current_clues_list, gr.update(visible=True, value=error), "", "", format_clues_history(current_clues_list)
112
+
113
+ if len(emojis) != 5 or not all(e in "🟩🟨πŸŸ₯⬛" for e in emojis):
114
+ error = "Emojis must be 5 characters long and contain only 🟩, 🟨, πŸŸ₯, or ⬛."
115
+ return current_clues_list, gr.update(visible=True, value=error), "", "", format_clues_history(current_clues_list)
116
+
117
+ # 2. Update State
118
+ new_clue = (word, emojis)
119
+ if new_clue not in current_clues_list:
120
+ current_clues_list.append(new_clue)
121
+
122
+ # 3. Core Logic
123
+ remaining_words = filter_words_by_clues(WORD_LIST, current_clues_list)
124
+ best_guess, status_text = get_best_guess(remaining_words, WORD_LIST)
125
+
126
+ # 4. Format Output
127
+ history_md = format_clues_history(current_clues_list)
128
+
129
+ if not remaining_words:
130
+ best_guess_str = "πŸ˜•"
131
+ status_text = "No words match your clues. There might be an error in your input. Please reset and try again."
132
+ elif len(remaining_words) == 1:
133
+ best_guess_str = remaining_words[0].upper()
134
+ status_text = "πŸŽ‰ Found it! This is the only possible word."
135
+ else:
136
+ best_guess_str = best_guess.upper()
137
+
138
+ return current_clues_list, gr.update(visible=False, value=""), best_guess_str, status_text, history_md
139
+
140
+ def get_other_suggestions(current_clues_list):
141
+ """Handles the 'Get Other Suggestions' button click."""
142
+ if not current_clues_list:
143
+ return "Enter at least one guess to get suggestions."
144
+
145
+ remaining_words = filter_words_by_clues(WORD_LIST, current_clues_list)
146
+
147
+ if not remaining_words:
148
+ return "No words match the current clues."
149
+
150
+ if len(remaining_words) == 1:
151
+ return f"Only one word remains: **{remaining_words[0].upper()}**"
152
+
153
+ letter_freq = get_letter_frequency(remaining_words)
154
+ scored_words = sorted([(word, score_word(word, letter_freq)) for word in remaining_words], key=lambda x: x[1], reverse=True)
155
+
156
+ # Format suggestions into a markdown list
157
+ suggestions_md = f"### Top Suggestions ({len(remaining_words)} words remain)\n"
158
+ for word, score in scored_words[:10]:
159
+ suggestions_md += f"- **{word.upper()}**\n"
160
+
161
+ if len(scored_words) > 10:
162
+ suggestions_md += f"\n...and {len(scored_words) - 10} more."
163
+
164
+ return suggestions_md
165
+
166
+ def reset_session():
167
+ """Clears all inputs, outputs, and the session state."""
168
+ return [], "", "", "", "No guesses yet. Enter your first guess above.", "", gr.update(visible=False, value="")
169
+
170
+ def format_clues_history(clues_list):
171
+ """Converts the list of clues into a markdown string for display."""
172
+ if not clues_list:
173
+ return "No guesses yet. Enter your first guess above."
174
+
175
+ md = "### Your Guess History\n"
176
+ for word, emojis in clues_list:
177
+ md += f"- `{word.upper()}` -> {emojis}\n"
178
+ return md
179
+
180
+ # --- Gradio UI Layout ---
181
+
182
+ with gr.Blocks(theme=gr.themes.Soft(), title="Wordle Solver Bot") as demo:
183
+ # State object to store the list of clues for the session
184
+ session_clues = gr.State([])
185
+
186
+ gr.Markdown("# 🧩 Wordle Solver Bot")
187
+ gr.Markdown("Enter your Wordle guesses below, and I'll suggest the best next word to try!")
188
+
189
+ with gr.Row():
190
+ with gr.Column(scale=2):
191
+ word_input = gr.Textbox(label="Guessed Word", placeholder="e.g., CRANE")
192
+ emoji_input = gr.Textbox(label="Emoji Results", placeholder="e.g., πŸŸ₯🟨🟩πŸŸ₯πŸŸ₯")
193
+ error_box = gr.Textbox(label="Error", visible=False, interactive=False)
194
+ with gr.Row():
195
+ submit_button = gr.Button("Submit Guess", variant="primary")
196
+ other_button = gr.Button("Get Other Suggestions")
197
+ reset_button = gr.Button("Reset Session", variant="stop")
198
+
199
+ with gr.Column(scale=3):
200
+ best_guess_output = gr.Textbox(label="πŸ’‘ Best Next Guess", interactive=False)
201
+ status_output = gr.Textbox(label="πŸ“Š Status", interactive=False)
202
+
203
+ with gr.Row():
204
+ with gr.Column():
205
+ history_output = gr.Markdown("No guesses yet. Enter your first guess above.")
206
+ with gr.Column():
207
+ other_suggestions_output = gr.Markdown("")
208
+
209
+ # --- Event Handlers ---
210
+ submit_button.click(
211
+ fn=process_guess,
212
+ inputs=[word_input, emoji_input, session_clues],
213
+ outputs=[session_clues, error_box, best_guess_output, status_output, history_output]
214
+ )
215
+
216
+ other_button.click(
217
+ fn=get_other_suggestions,
218
+ inputs=[session_clues],
219
+ outputs=[other_suggestions_output]
220
+ )
221
+
222
+ reset_button.click(
223
+ fn=reset_session,
224
+ inputs=[],
225
+ outputs=[session_clues, word_input, emoji_input, best_guess_output, history_output, status_output, error_box]
226
+ )
227
+
228
+ if __name__ == "__main__":
229
+ if not WORD_LIST:
230
+ print("Could not start the application because 'words.txt' is missing or empty.")
231
+ else:
232
+ print("Starting Gradio app... Access it at the URL provided below.")
233
+ demo.launch()