# Importing required libraries import gradio as gr from PIL import Image import random import os # Define the folder containing images CELEB_FOLDER = "./Celebs" # Get the list of celebrity images from the folder celebs = {os.path.splitext(file)[0]: os.path.join(CELEB_FOLDER, file) for file in os.listdir(CELEB_FOLDER)} # Define pixel sizes for different levels of clarity PIXEL_SIZES = [128, 96, 64, 48, 32, 24, 16, 12, 8, 4, 2] # Initialize global variables current_image = None current_name = None current_pixel_size = 256 # Function to pixelate an image def pixelate(image, pixel_size): # Reduce the image size small = image.resize((image.size[0] // pixel_size, image.size[1] // pixel_size), Image.Resampling.NEAREST) # Scale back to the original size return small.resize(image.size, Image.Resampling.NEAREST) # Start a new game def start_game(): global current_image, current_name, current_pixel_size current_name, image_path = random.choice(list(celebs.items())) current_image = Image.open(image_path) current_pixel_size = PIXEL_SIZES[0] pixelated_image = pixelate(current_image, current_pixel_size) return pixelated_image, "Image Loaded. Guess the Celebrity!" # Reveal more of the image def clear_more(): global current_pixel_size if current_pixel_size > PIXEL_SIZES[-1]: current_pixel_size = PIXEL_SIZES[PIXEL_SIZES.index(current_pixel_size) + 1] pixelated_image = pixelate(current_image, current_pixel_size) return pixelated_image, "Getting clearer! Keep guessing!" # Check the user's guess def check_guess(user_guess): if user_guess.strip().lower() == current_name.strip().lower(): return "Correct! 🎉 You guessed it right!" else: return "Incorrect. Keep trying!" # Reveal the answer def reveal_answer(): return f"The correct answer is: {current_name}!" # Create the Gradio interface with gr.Blocks() as demo: gr.Markdown("# 🎭 Guess the Celebrity Game!") gr.Markdown("Can you identify the celebrity as the image becomes clearer?") with gr.Row(): pixelated_image = gr.Image(type="pil", label="Pixelated Image") answer_input = gr.Textbox(label="Your Guess", placeholder="Type your guess here...") result = gr.Label(label="Game Status") with gr.Row(): start_button = gr.Button("Start Game") clear_button = gr.Button("Clear More") guess_button = gr.Button("Submit Guess") reveal_button = gr.Button("Reveal Answer") start_button.click(start_game, inputs=[], outputs=[pixelated_image, result]) clear_button.click(clear_more, inputs=[], outputs=[pixelated_image, result]) guess_button.click(check_guess, inputs=answer_input, outputs=result) reveal_button.click(reveal_answer, inputs=[], outputs=result) demo.launch(debug=True, show_error=True)