Spaces:
Runtime error
Runtime error
fix toggle to show labels
Browse files18 unmodified lines1920212223242525 unmodified lines515253545556575859606162636465666768697071727374757677787 unmodified lines8687888990919215 unmodified lines10810911011111211311411511611711811912012112212312412512611 unmodified lines13813914014114214314414514618 unmodified lines16516616716816917017117217317417517617717818 unmodified lines# stats stufffrom pymongo.mongo_client import MongoClientfrom pymongo.server_api import ServerApiimport time # Make sure to import the time module25 unmodified linesimage_paths_global = []def update_labels(show_labels):if show_labels:# return [(path, label) for path, label in zip(image_paths_global, image_labels_global)]updated_gallery = [(path, label) for path, label in zip(image_paths_global, image_labels_global)]else:# return [(path, "") for path in image_paths_global] # Empty string as label to hide themupdated_gallery = [(path, "") for path in image_paths_global] # Empty string as label to hide themreturn updated_gallerydef generate_images_wrapper(prompts, pw, model, show_labels):global image_paths_global, image_labels_globalimage_paths, image_labels = generate_images(prompts, pw, model)image_paths_global = image_paths # Store paths globallyif show_labels:image_labels_global = image_labels # Store labels globally if showing labels is enabledelse:image_labels_global = [""] * len(image_labels) # Use empty labels if showing labels is disabled# Modify the return statement to not use labels if show_labels is Falseimage_data = [(path, label if show_labels else "") for path, label in zip(image_paths, image_labels)]return image_data # Return image paths with or without labels based on the toggledef download_image(url):response = requests.get(url)7 unmodified lineswith zipfile.ZipFile(zip_file_path, 'w') as zipf:for image_url, _ in image_paths_and_labels:image_content = download_image(image_url)# Generate a random filename for the imagerandom_filename = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) + ".png"# Write the image content to the zip file with the random filenamezipf.writestr(random_filename, image_content)15 unmodified linesif pw != os.getenv("PW"):raise gr.Error("Invalid password. Please try again.")image_paths = [] # Initialize a list to hold paths of generated imagesimage_labels = [] # Initialize a list to hold labels of generated imagesusers = [] # Initialize a list to hold user initials# Split the prompts string into individual prompts based on semicolon separationprompts_list = prompts.split(';')for entry in prompts_list:entry_parts = entry.split('-', 1) # Split by the first dash foundif len(entry_parts) != 2:raise gr.Error("Invalid prompt format. Please ensure it is in 'initials-prompt' format.")user_initials, text = entry_parts[0].strip(), entry_parts[1].strip() # Extract user initials and the promptusers.append(user_initials) # Append user initials to the listtry:11 unmodified linesgen_time = end_time - start_time # total generation timeimage_url = response.data[0].urlimage_label = f"User: {user_initials}, Prompt: {text}" # Creating a label for the image including user initialstry:mongo_collection.insert_one({"user": user_initials, "text": text, "model": model, "image_url": image_url, "gen_time": gen_time, "timestamp": time.time()})except Exception as e:print(e)18 unmodified linesplaceholder="Enter your text and then click on the \"Image Generate\" button")model = gr.Dropdown(choices=["dall-e-2", "dall-e-3"], label="Model", value="dall-e-3")#MH TODO: not toggling properlyshow_labels = gr.Checkbox(label="Show Image Labels", value=True)btn = gr.Button("Generate Images")output_images = gr.Gallery(label="Image Outputs", show_label=True, columns=[3], rows=[1], object_fit="contain",height="auto", allow_preview=False)text.submit(fn=generate_images_wrapper, inputs=[text, pw, model], outputs=output_images, api_name="generate_image")# btn.click(fn=generate_images_wrapper, inputs=[text, pw, model], outputs=output_images, api_name=False)btn.click(fn=generate_images_wrapper, inputs=[text, pw, model, show_labels], outputs=output_images, api_name=False)show_labels.change(fn=update_labels, inputs=[show_labels], outputs=[output_images])18 unmodified lines1920212223242525 unmodified lines515253545556575859606162636465666768697 unmodified lines77787980818215 unmodified lines989910010110210310410510610710810911011111211311411511611711811911 unmodified lines13113213313413513613713813914014118 unmodified lines16016116216316416516616716816917017117218 unmodified lines# stats stufffrom pymongo.mongo_client import MongoClientfrom pymongo.server_api import ServerApiimport time25 unmodified linesimage_paths_global = []def update_labels(show_labels):updated_gallery = [(path, label if show_labels else "") for path, label in zip(image_paths_global, image_labels_global)]return updated_gallerydef generate_images_wrapper(prompts, pw, model, show_labels):global image_paths_global, image_labels_globalimage_paths, image_labels = generate_images(prompts, pw, model)image_paths_global = image_paths# store this as a global so we can handle toggle stateimage_labels_global = image_labelsimage_data = [(path, label if show_labels else "") for path, label in zip(image_paths, image_labels)]return image_datadef download_image(url):response = requests.get(url)7 unmodified lineswith zipfile.ZipFile(zip_file_path, 'w') as zipf:for image_url, _ in image_paths_and_labels:image_content = download_image(image_url)random_filename = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) + ".png"# Write the image content to the zip file with the random filenamezipf.writestr(random_filename, image_content)15 unmodified linesif pw != os.getenv("PW"):raise gr.Error("Invalid password. Please try again.")image_paths = [] # holds urls of imagesimage_labels = [] # shows the prompt in the gallery above the imageusers = [] # adds the user to the label# Split the prompts string into individual prompts based on semicolon separationprompts_list = prompts.split(';')for entry in prompts_list:entry_parts = entry.split('-', 1) # Split by the first dash foundif len(entry_parts) == 2:#raise gr.Error("Invalid prompt format. Please ensure it is in 'initials-prompt' format.")user_initials, text = entry_parts[0].strip(), entry_parts[1].strip() # Extract user initials and the promptelse:text = entry.strip() # If no initials are provided, use the entire prompt as the textuser_initials = ""users.append(user_initials) # Append user initials to the listtry:11 unmodified linesgen_time = end_time - start_time # total generation timeimage_url = response.data[0].url# conditionally render the user to the label with the promptimage_label = f"Prompt: {text}" if user_initials == "" else f"User: {user_initials}, Prompt: {text}"try:# Save the prompt, model, image URL, generation time and creation timestamp to the databasemongo_collection.insert_one({"user": user_initials, "text": text, "model": model, "image_url": image_url, "gen_time": gen_time, "timestamp": time.time()})except Exception as e:print(e)18 unmodified linesplaceholder="Enter your text and then click on the \"Image Generate\" button")model = gr.Dropdown(choices=["dall-e-2", "dall-e-3"], label="Model", value="dall-e-3")show_labels = gr.Checkbox(label="Show Image Labels", value=False)btn = gr.Button("Generate Images")output_images = gr.Gallery(label="Image Outputs", show_label=True, columns=[3], rows=[1], object_fit="contain",height="auto", allow_preview=False)#trigger generation either through hitting enter in the text field, or clicking the button.text.submit(fn=generate_images_wrapper, inputs=[text, pw, model, show_labels], outputs=output_images, api_name="generate_image") # Generate an api endpoint in Gradio / HFbtn.click(fn=generate_images_wrapper, inputs=[text, pw, model, show_labels], outputs=output_images, api_name=False)show_labels.change(fn=update_labels, inputs=[show_labels], outputs=[output_images])
app.py+21-27