Phone_C / app.py
gaur3009's picture
Update app.py
88523c4 verified
raw
history blame
6.67 kB
import gradio as gr
import requests
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from tqdm import tqdm
import numpy as np
import time
repo = "artificialguybr/TshirtDesignRedmond-V2"
# Generate design based on prompts
def infer(color_prompt, phone_type_prompt, design_prompt):
prompt = (
f"A single vertical {color_prompt} colored {phone_type_prompt} back cover featuring a bold {design_prompt} design on the front, hanging on the plain wall. The soft light and shadows, creating a striking contrast against the minimal background, evoking modern sophistication."
)
full_prompt = f"{prompt}"
print("Generating image with prompt:", full_prompt)
api_url = f"https://api-inference.huggingface.co/models/{repo}"
headers = {}
payload = {
"inputs": full_prompt,
"parameters": {
"negative_prompt": "(worst quality, low quality, lowres, oversaturated, grayscale, bad photo:1.4)",
"num_inference_steps": 30,
"scheduler": "DPMSolverMultistepScheduler",
},
}
error_count = 0
pbar = tqdm(total=None, desc="Loading model")
while True:
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code == 200:
speech_text = f"Your design is generated with the color '{color_prompt}', mobile type '{phone_type_prompt}', and design '{design_prompt}'."
return Image.open(BytesIO(response.content)), speech_text
elif response.status_code == 503:
time.sleep(1)
pbar.update(1)
elif response.status_code == 500 and error_count < 5:
time.sleep(1)
error_count += 1
else:
raise Exception(f"API Error: {response.status_code}")
def save_design(image, color_prompt, phone_type_prompt, design_prompt):
# Convert NumPy array to PIL Image
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
# Add caption
draw = ImageDraw.Draw(image)
caption = f"Color: {color_prompt}\nMobile Type: {phone_type_prompt}\nDesign: {design_prompt}"
font_size = 20
try:
# Attempt to load a default font
font = ImageFont.truetype("arial.ttf", font_size)
except IOError:
font = ImageFont.load_default()
# Calculate position for text
text_width, text_height = font.getsize_multiline(caption) # Updated function
position = (10, image.height - text_height - 10) # Bottom-left corner with padding
# Add caption to the image
draw.multiline_text(position, caption, fill="white", font=font)
# Save the image
file_path = "saved_design_with_caption.png"
image.save(file_path)
return f"Design saved as {file_path}!"
# HTML-based carousel content
carousel_html = """
<div class="carousel">
<div class="slides">
<img src="https://via.placeholder.com/300x400.png?text=Design+1" alt="Design 1">
<img src="https://via.placeholder.com/300x400.png?text=Design+2" alt="Design 2">
<img src="https://via.placeholder.com/300x400.png?text=Design+3" alt="Design 3">
</div>
</div>
<style>
.carousel {
display: flex;
overflow: hidden;
width: 100%;
max-width: 800px;
margin: 0 auto;
}
.slides {
display: flex;
transition: transform 0.5s ease-in-out;
animation: slide 10s infinite;
}
.slides img {
width: 300px;
height: 400px;
margin: 0 10px;
}
@keyframes slide {
0%, 20% { transform: translateX(0); }
40%, 60% { transform: translateX(-320px); }
80%, 100% { transform: translateX(-640px); }
}
</style>
"""
# Custom CSS for animations
custom_css = """
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
margin: 0;
padding: 0;
overflow: hidden;
}
body::before {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(-45deg, #ff9a9e, #fad0c4, #fbc2eb, #8fd3f4);
background-size: 400% 400%;
z-index: -1;
animation: gradientShift 15s ease infinite;
}
@keyframes gradientShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
"""
# Gradio interface
with gr.Blocks(css=custom_css) as interface:
gr.Markdown("# **AI Phone Cover Designer**")
gr.Markdown("Create custom phone covers with AI. Save your designs for future use.")
# Navigation Tabs
with gr.Tabs():
with gr.Tab("Home"):
gr.Markdown("### Welcome to the **AI Phone Cover Designer**!")
gr.Markdown("Below is a carousel showcasing some of the saved designs.")
gr.HTML(carousel_html)
with gr.Tab("Design"):
with gr.Row():
with gr.Column(scale=1):
color_prompt = gr.Textbox(label="Color", placeholder="E.g., Red")
phone_type_prompt = gr.Textbox(label="Mobile type", placeholder="E.g., iPhone, Samsung")
design_prompt = gr.Textbox(label="Design Details", placeholder="E.g., Bold stripes with geometric patterns")
generate_button = gr.Button("Generate Design")
save_button = gr.Button("Save Design")
with gr.Column(scale=1):
output_image = gr.Image(label="Generated Design")
output_message = gr.Textbox(label="AI Assistant Message", interactive=False)
# Button Actions
generate_button.click(
infer,
inputs=[color_prompt, phone_type_prompt, design_prompt],
outputs=[output_image, output_message],
)
save_button.click(
save_design,
inputs=[output_image, color_prompt, phone_type_prompt, design_prompt],
outputs=output_message,
)
with gr.Tab("About"):
gr.Markdown("""
## About AI Phone Cover Maker
The **AI Phone Cover Maker** is a cutting-edge tool designed to help users create personalized phone cover designs quickly and easily.
Powered by AI, it uses advanced image generation techniques to craft unique, high-quality designs for any mobile device.
### Features:
- Create custom designs using simple prompts.
- Generate designs for various phone models.
- Save your designs for future use.
Start designing today and bring your creative ideas to life!
""")
interface.launch(debug=True)