Spaces:
Runtime error
Runtime error
app.py
Browse files
app.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import time
|
4 |
+
import enum
|
5 |
+
import uuid
|
6 |
+
import base64
|
7 |
+
import requests
|
8 |
+
import structlog
|
9 |
+
import gradio as gr
|
10 |
+
import random
|
11 |
+
import functools
|
12 |
+
|
13 |
+
|
14 |
+
logger = structlog.getLogger()
|
15 |
+
replicate_api_key = os.environ.get('REPLICATE_KEY')
|
16 |
+
|
17 |
+
# Everyone gets the same order of words
|
18 |
+
random.seed(42)
|
19 |
+
with open('five_letter_words.txt') as f:
|
20 |
+
words = f.read().splitlines()
|
21 |
+
random.shuffle(words)
|
22 |
+
random.seed()
|
23 |
+
|
24 |
+
|
25 |
+
class Image:
|
26 |
+
@classmethod
|
27 |
+
def create(cls, prompt, n=1, response_format="url", model="fofr", size="256x256"):
|
28 |
+
logger.info(f'requesting Image with prompt={prompt}, n={n}, response_format={response_format}, model={model}, size={size}...')
|
29 |
+
width, height = size.split('x')
|
30 |
+
width, height = int(width), int(height)
|
31 |
+
resp = requests.post(
|
32 |
+
"https://api.replicate.com/v1/predictions",
|
33 |
+
headers={"Content-Type": "application/json", "Authorization": f"Token {replicate_api_key}"},
|
34 |
+
json={"version": "a83d4056c205f4f62ae2d19f73b04881db59ce8b81154d314dd34ab7babaa0f1", "input": {
|
35 |
+
"prompt": prompt,
|
36 |
+
"width": width, "height": height,
|
37 |
+
"num_images": n,
|
38 |
+
}},
|
39 |
+
)
|
40 |
+
resp = resp.json()
|
41 |
+
sleeps = 0
|
42 |
+
while resp.get("status", "fail").lower() not in {"fail", "succeeded"}:
|
43 |
+
if sleeps >= 10:
|
44 |
+
raise Exception('Error generating image', resp)
|
45 |
+
logger.info(f"Sleeping 1...")
|
46 |
+
time.sleep(1)
|
47 |
+
sleeps += 1
|
48 |
+
resp = requests.get(f"https://api.replicate.com/v1/predictions/{resp['id']}", headers={"Content-Type": "application/json", "Authorization": f"Token {replicate_api_key}"})
|
49 |
+
resp = resp.json()
|
50 |
+
logger.info('received Image...')
|
51 |
+
url = resp['output'][0]
|
52 |
+
# Get the MIME type of the image (e.g., 'image/jpeg', 'image/png')
|
53 |
+
mime_type = f"image/{url.rsplit('.', 1)[-1]}"
|
54 |
+
# Encode to base64 and format as a data URI
|
55 |
+
return f"data:{mime_type};base64," + base64.b64encode(requests.get(url).content).decode()
|
56 |
+
|
57 |
+
|
58 |
+
@functools.cache
|
59 |
+
def get_image(word_num, guess_num):
|
60 |
+
prompt = words[word_num]
|
61 |
+
return Image.create(prompt)
|
62 |
+
|
63 |
+
|
64 |
+
def display_images_base64(image_strings):
|
65 |
+
# Start of the HTML string
|
66 |
+
html = '<html><body><div style="display: flex; flex-wrap: wrap;">'
|
67 |
+
# Template for an individual image
|
68 |
+
img_template = '<img src="{}" style="width: 30%; margin: 1%;" />'
|
69 |
+
# Loop through the list of image strings and append each to the HTML string
|
70 |
+
for img_str in image_strings:
|
71 |
+
html += img_template.format(img_str)
|
72 |
+
# Close the div and body tags
|
73 |
+
html += '</div></body></html>'
|
74 |
+
return html
|
75 |
+
|
76 |
+
|
77 |
+
def guess_word(word_num, guess, history=None):
|
78 |
+
word_num = abs(word_num) % len(words)
|
79 |
+
target = words[word_num]
|
80 |
+
guess = guess.lower()
|
81 |
+
feedback = []
|
82 |
+
|
83 |
+
if history is None:
|
84 |
+
history = {}
|
85 |
+
if word_num not in history:
|
86 |
+
history[word_num] = {
|
87 |
+
'guess': [],
|
88 |
+
'image': [],
|
89 |
+
}
|
90 |
+
|
91 |
+
if len(guess) != len(target):
|
92 |
+
feedback_str = "Guess must be {} letters long".format(len(target))
|
93 |
+
else:
|
94 |
+
for i, char in enumerate(guess):
|
95 |
+
if char == target[i]:
|
96 |
+
feedback.append('π©') # Green for correct position
|
97 |
+
elif char in target:
|
98 |
+
feedback.append('π¨') # Yellow for correct letter, wrong position
|
99 |
+
else:
|
100 |
+
feedback.append('β¬') # Black for incorrect letter
|
101 |
+
feedback_str = "".join(feedback)
|
102 |
+
|
103 |
+
# Update and return the history with the current guess feedback
|
104 |
+
history[word_num]['guess'].append(f"{guess}: {feedback_str}")
|
105 |
+
|
106 |
+
# Get and update the image history
|
107 |
+
new_image = get_image(word_num, len(history[word_num]['guess']) + 1)
|
108 |
+
history[word_num]['image'].append(new_image)
|
109 |
+
|
110 |
+
return feedback_str, '\n'.join(history[word_num]['guess']), display_images_base64(history[word_num]['image']), history
|
111 |
+
|
112 |
+
interface = gr.Interface(fn=guess_word,
|
113 |
+
inputs=[
|
114 |
+
gr.Number(value=random.randint(0, 100_000), label='Word number (Cannot be empty)'),
|
115 |
+
gr.Textbox(lines=1, label="Enter your guess (Cannot be empty)"),
|
116 |
+
gr.State()],
|
117 |
+
outputs=["text", gr.Textbox(label="Guess History", interactive=False, lines=10), gr.HTML(label="Guess Images"), gr.State()],
|
118 |
+
title="Wordle with Gradio",
|
119 |
+
description="A simple Wordle clone with guess history. Try to guess the word 'python'!",
|
120 |
+
allow_flagging="never")
|
121 |
+
|
122 |
+
interface.launch()
|