Spaces:
Runtime error
Runtime error
import os | |
from dotenv import load_dotenv | |
import gradio as gr | |
from groq import Groq | |
import json | |
import uuid | |
import requests | |
# Load environment variables from .env file | |
load_dotenv() | |
PRODIA_API_KEY = "391c48f4-8638-4f3f-a0d0-d84384ba8979" | |
PRODIA_URL_GENERATE = "https://api.prodia.com/v1/sd/generate" | |
PRODIA_URL_JOB = "https://api.prodia.com/v1/job/" | |
def generate_image_from_prompt(prompt): | |
payload = { | |
"model": "amIReal_V41.safetensors [0a8a2e61]", | |
"prompt": prompt, | |
"negative_prompt": "(3d, render, cgi, doll, painting, fake, cartoon, 3d modeling:1.4), (worst quality, low quality:1.4), monochrome, navel, zombie, overexposure, watermark, text, bad anatomy, bad hand, extra hands, extra fingers, too many fingers, fused fingers, bad arm, distorted arm, extra arms, fused arms, extra legs, missing leg, disembodied leg, extra nipples, detached arm, liquid hand, inverted hand, disembodied limb, oversized head, extra body, large breasts, extra navel, easynegative, (hair between eyes),sketch, duplicate, ugly, huge eyes, text, logo, worst face, (bad and mutated hands:1.3), (blurry:2.0), horror, geometry, bad_prompt, (bad hands), (missing fingers), multiple limbs, bad anatomy, (interlocked fingers:1.2), Ugly Fingers, (extra digit and hands and fingers and legs and arms:1.4), (deformed fingers:1.2), (long fingers:1.2),(bad-artist-anime), bad-artist, bad hand, extra legs ,(ng_deepnegative_v1_75t), ((badhandv4)), easynegative, FastNegativeV2", | |
"steps": 20, | |
"cfg_scale": 7, | |
"seed": -1, | |
"upscale": False, | |
"sampler": "DPM++ 2M Karras", | |
"width": 640, | |
"height": 1024 | |
} | |
headers = { | |
"accept": "application/json", | |
"content-type": "application/json", | |
"X-Prodia-Key": PRODIA_API_KEY | |
} | |
response = requests.post(PRODIA_URL_GENERATE, json=payload, headers=headers) | |
response_data = response.json() | |
return response_data.get("job") | |
def check_job_status(job_id): | |
headers = { | |
"accept": "application/json", | |
"X-Prodia-Key": PRODIA_API_KEY | |
} | |
response = requests.get(f"{PRODIA_URL_JOB}{job_id}", headers=headers) | |
return response.json() | |
def download_image(image_url, file_path): | |
response = requests.get(image_url) | |
with open(file_path, 'wb') as file: | |
file.write(response.content) | |
def process_json_files(): | |
prompt_directory = "prompt" | |
image_directory = "images" | |
if not os.path.exists(image_directory): | |
os.makedirs(image_directory) | |
for filename in os.listdir(prompt_directory): | |
if filename.endswith(".json"): | |
file_path = os.path.join(prompt_directory, filename) | |
with open(file_path, 'r') as json_file: | |
data = json.load(json_file) | |
prompt = data.get("prompt") | |
if prompt: | |
job_id = generate_image_from_prompt(prompt) | |
if job_id: | |
placeholder_path = os.path.join(image_directory, f"{job_id}.png") | |
with open(placeholder_path, 'wb') as placeholder: | |
placeholder.write(b'') # Create an empty placeholder file | |
# Polling for job completion | |
while True: | |
job_status = check_job_status(job_id) | |
if job_status.get("status") == "succeeded": | |
image_url = job_status.get("imageUrl") | |
if image_url: | |
download_image(image_url, placeholder_path) | |
print(f"Image downloaded and saved to {placeholder_path}") | |
break | |
elif job_status.get("status") == "failed": | |
print(f"Job {job_id} failed.") | |
break | |
def roleplay_input_function(age, gender, sexual_orientation, physique, nationality, roleplay_scenario, fetishes_kinks, explicit_level, emotions_dynamics, consent_importance): | |
# Access the API key from the environment variable | |
api_key = os.getenv("GROQ_API_KEY") | |
# Create the client with the API key | |
client = Groq(api_key=api_key) | |
# Prepare the message content | |
user_content = f"Age: {age}, Gender: {gender}, Sexual Orientation: {sexual_orientation}, Physique: {physique}, Nationality: {nationality}, Roleplay Scenario: {roleplay_scenario}, Fetishes/Kinks: {fetishes_kinks}, Explicit Level: {explicit_level}, Emotions/Dynamics: {emotions_dynamics}, Consent Importance: {consent_importance}" | |
# Send the message to Groq | |
completion = client.chat.completions.create( | |
model="llama-3.1-70b-versatile", | |
messages=[ | |
{ | |
"role": "system", | |
"content": "You are an expert prompt engineer specializing in creating highly detailed and dynamic positive prompts for image generation models such as Stable Diffusion. Your primary objective is to assist the user in crafting comprehensive, versatile, and richly descriptive positive prompts that ensure the generation of high-quality and diverse human model images in various poses and settings.\n\nGuidelines for Creating Positive Prompts:\nWhen generating a positive prompt, ensure that it includes the following components to maximize image quality and diversity:\n\nAdjective:\nPurpose: Sets the overall mood or quality of the image.\nExamples: \"elegant,\" \"dynamic,\" \"vibrant,\" \"serene.\"\n\nGender:\nPurpose: Specifies the gender of the human model.\nOptions: \"male,\" \"female,\" \"non-binary,\" etc.\n\nAge Group:\nPurpose: Defines the age category of the model.\nExamples: \"child,\" \"teenager,\" \"adult,\" \"elderly.\"\n\nDistinctive Features:\nPurpose: Highlights unique physical attributes to add character and individuality.\nExamples: \"long flowing hair,\" \"scar over the left eye,\" \"athletic build.\"\n\nAttire/Style:\nPurpose: Describes the clothing and fashion style to establish the aesthetic.\nExamples: \"casual summer outfit,\" \"traditional Japanese kimono,\" \"futuristic armor.\"\n\nSpecific Pose:\nPurpose: Defines the exact posture or stance to capture the desired action or emotion.\nExamples: \"standing with arms crossed,\" \"mid-jump action pose,\" \"sitting gracefully.\"\n\nActivity/Action:\nPurpose: Describes what the model is doing to add dynamism and context.\nExamples: \"playing a violin,\" \"running through a field,\" \"reading a book.\"\n\nEnvironment/Background:\nPurpose: Sets the scene and provides contextual backdrop.\nExamples: \"in a bustling cityscape,\" \"amidst a serene forest,\" \"on a sandy beach.\"\n\nLighting Conditions:\nPurpose: Defines the lighting to enhance mood and realism.\nExamples: \"soft natural lighting,\" \"dramatic spotlighting,\" \"sunset glow.\"\n\nSeason/Time of Day:\nPurpose: Specifies the temporal setting to influence the ambiance.\nExamples: \"spring morning,\" \"winter evening,\" \"autumn dusk.\"\n\nAdditional Attributes:\nPurpose: Any other relevant details that add uniqueness and richness to the image.\nExamples: \"holding a bouquet of flowers,\" \"wearing stylish sunglasses,\" \"with a confident smile.\"\n\nEnhancing Quality and Diversity:\nDetailed Descriptions: Use precise and vivid language to clearly convey each component.\nVariety: Mix and match different elements to create unique and diverse prompts.\nBalance: Ensure that the prompt is detailed enough to guide the model but flexible enough to allow creativity.\nConsistency: Maintain a consistent level of detail across all components to ensure uniform image quality.\n\nIncorporate Quality Enhancers:\nInclude terms that explicitly promote high-quality image generation:\n\"highly detailed\"\n\"realistic textures\"\n\"photorealistic\"\n\"ultra-high resolution\"\n\nExample Positive Prompts:\nExample 1: Elegant Female in a Modern Setting\n```\nA graceful female adult with long flowing hair dressed in a modern casual outfit, standing with arms crossed, reading a book, in a bustling cityscape, soft natural lighting, spring morning, holding a stylish handbag, highly detailed, realistic textures, photorealistic, ultra-high resolution.\n```\n\nExample 2: Athletic Male in Action\n```\nA muscular male teenager with short curly hair dressed in sporty active gear, mid-jump action pose, playing basketball, on an outdoor court, dynamic sunlight with strong shadows, summer afternoon, wearing stylish sneakers, highly detailed, realistic textures, photorealistic, ultra-high resolution.\n```\nExample 3: Non-Binary Individual in Artistic Pose\n```\nA poised non-binary adult with brightly dyed hair styled in braids, dressed in avant-garde fashion, sitting with one leg crossed over the other, holding a vintage camera, in an art studio with vibrant paintings on the walls, dramatic spotlighting, autumn evening, wearing unique accessories, highly detailed, realistic textures, photorealistic, ultra-high resolution.\n```\n\nInstructions for Use:\nGather Information: Ask the user for specific details regarding each component of the prompt.\nCustomize Components: Tailor each part of the prompt based on the user's descriptions to ensure uniqueness and relevance.\nEnsure Completeness: Make sure all components are addressed to create a comprehensive and effective positive prompt.\nIncorporate Enhancers: Add quality-enhancing terms to maintain high image standards.\nProvide Examples: Offer sample prompts to guide the user and showcase the template's effectiveness.\n\nFinal Output:\nGenerate the positive prompt following the structure and guidelines provided, ensuring it is rich in detail and variety to produce high-quality and diverse human model images.\n\nMake sure to return only the prompt without explanation at all and make sure it has variation in terms of location and pose also generate both NSFW and non-NSFW image. Prompt should be single entity no partner. Make sure each prompt has a different body pose\n\nplease return only in json format of 30 variant\n{\nprompt: \"######\",\nnsfw : \"yes/no\"\n}\n\nExample Interaction:\nUser Input: \"I want to create an image of a serene elderly man with a white beard, wearing traditional hiking gear, sitting peacefully by a mountain lake during sunset.\"\nGenerated Positive Prompt:\n```\nA serene male elderly with a white beard dressed in traditional hiking gear, sitting peacefully by a mountain lake, during sunset, soft natural lighting, autumn evening, holding a wooden walking stick, highly detailed, realistic textures, photorealistic, ultra-high resolution.\n ```" | |
}, | |
{ | |
"role": "user", | |
"content": user_content | |
} | |
], | |
temperature=1, | |
max_tokens=8000, | |
top_p=1, | |
stream=True, | |
stop=None, | |
) | |
# Collect the response | |
response = "" | |
for chunk in completion: | |
response += chunk.choices[0].delta.content or "" | |
# Debugging: Print the response | |
print("Response from Groq:", response) | |
# Parse the response if it's a JSON string | |
try: | |
response_data = json.loads(response) | |
except json.JSONDecodeError: | |
print("Failed to decode JSON response") | |
response_data = {"response": response} | |
# Generate a unique filename using UUID | |
unique_filename = f"{uuid.uuid4()}.json" | |
# Define the directory path | |
directory = "prompt" | |
if not os.path.exists(directory): | |
os.makedirs(directory) | |
print(f"Directory '{directory}' created.") | |
# Define the full path for the JSON file | |
file_path = os.path.join(directory, unique_filename) | |
# Store the response in a JSON file | |
try: | |
with open(file_path, 'w') as json_file: | |
json.dump(response_data, json_file, indent=4) | |
print(f"Response written to {file_path}") | |
except Exception as e: | |
print(f"Failed to write file: {e}") | |
# Ensure the 'images' directory exists | |
images_dir = "images" | |
if not os.path.exists(images_dir): | |
os.makedirs(images_dir) | |
# Loop through the JSON data to send prompts to Prodia | |
for item in response_data: | |
prompt = item.get("prompt") | |
if prompt: | |
print(f"Sending prompt to Prodia: {prompt}") # Log the prompt being sent | |
job_id = generate_image_from_prompt(prompt) | |
if job_id: | |
placeholder_path = os.path.join(images_dir, f"{job_id}.png") | |
with open(placeholder_path, 'wb') as placeholder: | |
placeholder.write(b'') # Create an empty placeholder file | |
# Polling for job completion | |
while True: | |
job_status = check_job_status(job_id) | |
if job_status.get("status") == "succeeded": | |
image_url = job_status.get("imageUrl") | |
if image_url: | |
download_image(image_url, placeholder_path) | |
print(f"Image downloaded and saved to {placeholder_path}") | |
break | |
elif job_status.get("status") == "failed": | |
print(f"Job {job_id} failed.") | |
break | |
return response | |
gender_identities = [ | |
"Male", "Female", "Transgender", "Non-binary", "Genderqueer", "Genderfluid", "Agender", "Bigender", "Polygender", "Demigender", "Intergender", "Pangender", "Androgynous" | |
] | |
sexual_orientations = [ | |
"Heterosexual", "Homosexual", "Bisexual", "Pansexual", "Asexual", "Demisexual", "Graysexual", "Queer", "Questioning", "Polysexual", "Omnisexual", "Androsexual", "Gynesexual", "Skoliosexual" | |
] | |
physiques = [ | |
"Ectomorph (lean and slender)", "Mesomorph (muscular and well-built)", "Endomorph (rounded and soft)", "Athletic", "Petite", "Curvy", "Plus-size", "Hourglass", "Pear-shaped", "Apple-shaped", "Slim", "Toned", "Muscular", "Bodybuilder", "Ripped", "Lean", "Stocky", "Average", "Lanky", "Chubby", "Overweight", "Obese", "Short", "Tall" | |
] | |
roleplays = [ | |
'Doctor/Patient', 'Teacher/Student', 'Boss/Secretary', 'Police Officer/Criminal', 'Stranger in a Bar', 'Massage Therapist/Client', 'Pizza Delivery Person/Customer', 'Handyman/Housewife', 'Vampire/Victim', 'Master/Slave', 'Age Play', 'Pet Play', 'Superhero/Damsel in Distress', 'Royalty/Servant', 'Prisoner/Guard', 'Nurse/Patient', 'Firefighter/Rescuee', 'Pilot/Flight Attendant', 'Stripper/Customer', 'Prostitute/Client', 'Photographer/Model', 'Soldier/Civilian', 'Alien/Human', 'Werewolf/Human', 'Ghost/Human', 'Pirate/Captive', 'Wizard/Apprentice', 'Scientist/Experiment Subject', 'Robot/Human', 'Cyborg/Human', 'Furry/Scalie', 'Babysitter/Parent', 'Pool Boy/Homeowner', 'Maid/Lord of the Manor', 'Hitchhiker/Driver', 'Stalker/Prey', 'Kidnapper/Victim', 'Interrogator/Prisoner', 'Therapist/Patient', 'Coach/Athlete', 'Priest/Penitent', 'Escort/Client', 'Gigolo/Customer', 'Exhibitionist/Voyeur', 'Cameraman/Porn Star', 'Dominatrix/Submissive', 'Cowboy/Cowgirl', 'Biker/Biker Chick', 'Knight/Prince or Princess', 'Viking/Captive', 'Gladiator/Sex Slave', 'Samurai/Geisha', 'Ninja/Target', 'Spy/Handler', 'Assassin/Mark', 'Detective/Suspect', 'Jedi/Sith', 'Superhero/Supervillain', 'Zombie/Survivor', 'Vampire Hunter/Vampire', 'Werewolf Hunter/Werewolf', 'Ghostbuster/Ghost', 'Demon Hunter/Demon', 'Angel/Human', 'Genie/Master', 'Mermaid/Sailor', 'Fairy/Tinkerer' | |
] | |
fetishes_kinks_acts = [ | |
"BDSM", "Foot Fetish", "Shoe Fetish", "Stockings and Pantyhose Fetish", "Lingerie Fetish", "Leather Fetish", "Latex and Rubber Fetish", "Exhibitionism", "Voyeurism", "Roleplaying", "Orgasm Control", "Edging", "Sensory Deprivation", "Sensory Play (e.g. ice, wax, feathers)", "Impact Play (e.g. spanking, flogging, paddling)", "Bondage (e.g. rope, handcuffs, tape)", "Flogging", "Wax play", "Electrical play", "Piercing play", "Choking/Breath play", "Human Furniture", "Water Sports (Urination)", "Scat Play (Feces)", "Blood Play", "Cuckolding", "Cuckqueaning", "Double Penetration", "Fisting", "Frottage", "Hand Jobs", "Masturbation", "Oral Sex", "Pegging", "Rimming", "Threesomes, Foursomes, Group Sex", "Swinging", "Tantric Sex", "Urethral Sounding", "Vaginal and Anal Stretching", "Dirty Talk", "Erotic Massage", "Body Worship", "Cross-dressing", "Ageplay", "Petplay" | |
] | |
explicit = ["mild", "moderate", "explicit"] | |
emotions_dynamics = [ | |
"Love", "Lust", "Passion", "Romance", "Affection", "Tenderness", "Desire", "Jealousy", "Possessiveness", "Anger", "Fear", "Curiosity", "Vulnerability", "Trust", "Submission", "Dominance", "Control", "Worship", "Teasing", "Denial", "Anticipation", "Surprise", "Humiliation", "Degradation", "Praise", "Discipline", "Seduction", "Flirtation", "Rejection", "Forgiveness", "Nurturing", "Empathy", "Understanding", "Respect", "Mystery", "Danger", "Protection", "Adventure", "Comfort", "Security", "Pleasure", "Sensual", "Intense", "Rough", "Gentle" | |
] | |
iface = gr.Interface( | |
fn=roleplay_input_function, | |
inputs=[ | |
gr.inputs.Textbox(label="What is your age?"), | |
gr.inputs.Dropdown(choices=gender_identities, label="What is your gender?"), | |
gr.inputs.Dropdown(choices=sexual_orientations, label="What is your sexual orientation?"), | |
gr.inputs.Dropdown(choices=physiques, label="What is the physique of the character?"), | |
gr.inputs.Textbox(label="What is the nationality of the character?"), | |
gr.inputs.Dropdown(choices=roleplays, label="What kind of roleplay scenario are you interested in?"), | |
gr.inputs.CheckboxGroup(choices=fetishes_kinks_acts, label="What fetishes, kinks, or specific acts would you like to include in the roleplay?"), | |
gr.inputs.Dropdown(choices=explicit, label="How explicit would you like the roleplay to be?"), | |
gr.inputs.CheckboxGroup(choices=emotions_dynamics, label="Would you like the roleplay to be more realistic or more fantastical, and are there any specific emotions or dynamics you'd like to incorporate?"), | |
gr.inputs.Textbox(label="How important is consent and communication within the roleplay for you?") | |
], | |
outputs="text" | |
) | |
iface.launch(share=True) |