Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- .DS_Store +0 -0
- .env +5 -0
- .gitattributes +3 -0
- .gradio/cached_examples/17/Enhanced Smile Result/297e6826d707efe59e6e/image.webp +0 -0
- .gradio/cached_examples/17/Enhanced Smile Result/63258dc188ae831c8922/image.webp +0 -0
- .gradio/cached_examples/17/log.csv +7 -0
- .gradio/certificate.pem +31 -0
- README.md +26 -7
- app.py +314 -0
- data/1.jpg +3 -0
- data/1.webp +0 -0
- data/1777043.jpg +3 -0
- data/2.webp +0 -0
- data/2807615.jpg +3 -0
- data/3.webp +0 -0
- data/76860.jpg +0 -0
- requirements.txt +4 -0
.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
.env
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Add your Gemini API key here
|
| 2 |
+
GOOGLE_API_KEY=AIzaSyCVzRDxkuvtaS1B22F_F-zl0ehhXR0nuU8
|
| 3 |
+
|
| 4 |
+
GEMINI_API_KEY=AIzaSyCVzRDxkuvtaS1B22F_F-zl0ehhXR0nuU8
|
| 5 |
+
|
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
data/1.jpg filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
data/1777043.jpg filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
data/2807615.jpg filter=lfs diff=lfs merge=lfs -text
|
.gradio/cached_examples/17/Enhanced Smile Result/297e6826d707efe59e6e/image.webp
ADDED
|
.gradio/cached_examples/17/Enhanced Smile Result/63258dc188ae831c8922/image.webp
ADDED
|
.gradio/cached_examples/17/log.csv
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Enhanced Smile Result,Processing Status,timestamp
|
| 2 |
+
"[{""image"": {""path"": "".gradio/cached_examples/17/Enhanced Smile Result/297e6826d707efe59e6e/image.webp"", ""url"": ""/gradio_api/file=/private/var/folders/k9/4nnkrkrs3sb3t80c0120tpl80000gr/T/gradio/e6f72632b86ca0f8af6c79451b685aa7b63f0403c3a6651387a5adfdab8b73f0/image.webp"", ""size"": null, ""orig_name"": null, ""mime_type"": null, ""is_stream"": false, ""meta"": {""_type"": ""gradio.FileData""}}, ""caption"": null}]",Note: The model returned a text response instead of an enhanced image: ,2025-04-16 14:42:18.166586
|
| 3 |
+
"[{""image"": {""path"": "".gradio/cached_examples/17/Enhanced Smile Result/63258dc188ae831c8922/image.webp"", ""url"": ""/gradio_api/file=/private/var/folders/k9/4nnkrkrs3sb3t80c0120tpl80000gr/T/gradio/b8cc3be88c50956dd06137dca273308c19d6d827dfcee57cdc68fbc10ad2894d/image.webp"", ""size"": null, ""orig_name"": null, ""mime_type"": null, ""is_stream"": false, ""meta"": {""_type"": ""gradio.FileData""}}, ""caption"": null}]","Note: The model returned a text response instead of an enhanced image: I
|
| 4 |
+
cannot fulfill your request to modify the provided image. The image contains text and does
|
| 5 |
+
not depict a person's face or teeth that can be enhanced with smile enhancement
|
| 6 |
+
techniques.
|
| 7 |
+
",2025-04-16 14:42:22.984487
|
.gradio/certificate.pem
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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rF2LN9d11TPA
|
| 29 |
+
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
| 30 |
+
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
| 31 |
+
-----END CERTIFICATE-----
|
README.md
CHANGED
|
@@ -1,12 +1,31 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 5.
|
| 8 |
app_file: app.py
|
| 9 |
-
pinned:
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: smile-enhancement-ai
|
| 3 |
+
emoji: 😁
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.20.1
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# Smile Enhancement AI
|
| 13 |
+
|
| 14 |
+
A simple, user-friendly application that uses Google's Gemini AI to enhance smiles in portrait photos. The app creates natural-looking smile enhancements with adjustable intensity levels.
|
| 15 |
+
|
| 16 |
+
## Features
|
| 17 |
+
|
| 18 |
+
- Simple upload interface - just drag and drop your photo
|
| 19 |
+
- Creates personalized, natural-looking smiles that suit the individual
|
| 20 |
+
- Preserves natural dental characteristics while making subtle enhancements
|
| 21 |
+
- Maintains each person's unique smile features and tooth coloration
|
| 22 |
+
- Enhances eye crinkles and cheek raising for authentic expressions
|
| 23 |
+
- Preserves facial identity while enhancing smiles
|
| 24 |
+
- Works with most portrait photos showing visible teeth
|
| 25 |
+
- No API key or login required
|
| 26 |
+
|
| 27 |
+
## Usage
|
| 28 |
+
|
| 29 |
+
1. Upload a clear selfie with a visible smile
|
| 30 |
+
2. Click "Enhance Smile with Natural Expressions" to process your image
|
| 31 |
+
3. Download your enhanced smile image
|
app.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import uuid
|
| 5 |
+
import tempfile
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import base64
|
| 9 |
+
import mimetypes
|
| 10 |
+
|
| 11 |
+
from google import genai
|
| 12 |
+
from google.genai import types
|
| 13 |
+
|
| 14 |
+
def save_binary_file(file_name, data):
|
| 15 |
+
with open(file_name, "wb") as f:
|
| 16 |
+
f.write(data)
|
| 17 |
+
|
| 18 |
+
def generate(text, file_name, api_key, model="gemini-2.0-flash-exp"):
|
| 19 |
+
# Initialize client using provided api_key (or fallback to env variable)
|
| 20 |
+
client = genai.Client(api_key=(api_key.strip() if api_key and api_key.strip() != ""
|
| 21 |
+
else os.environ.get("GEMINI_API_KEY")))
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
print("Uploading file to Gemini API...")
|
| 25 |
+
files = [ client.files.upload(file=file_name) ]
|
| 26 |
+
|
| 27 |
+
contents = [
|
| 28 |
+
types.Content(
|
| 29 |
+
role="user",
|
| 30 |
+
parts=[
|
| 31 |
+
types.Part.from_uri(
|
| 32 |
+
file_uri=files[0].uri,
|
| 33 |
+
mime_type=files[0].mime_type,
|
| 34 |
+
),
|
| 35 |
+
types.Part.from_text(text=text),
|
| 36 |
+
],
|
| 37 |
+
),
|
| 38 |
+
]
|
| 39 |
+
generate_content_config = types.GenerateContentConfig(
|
| 40 |
+
temperature=0, # Lower temperature for more consistent, conservative results
|
| 41 |
+
top_p=0.92,
|
| 42 |
+
max_output_tokens=8192,
|
| 43 |
+
response_modalities=["image", "text"],
|
| 44 |
+
response_mime_type="text/plain",
|
| 45 |
+
# Additional parameters to encourage subtle, natural results
|
| 46 |
+
safety_settings=[
|
| 47 |
+
{
|
| 48 |
+
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
| 49 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
| 50 |
+
}
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
text_response = ""
|
| 55 |
+
image_path = None
|
| 56 |
+
# Create a temporary file to potentially store image data
|
| 57 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 58 |
+
temp_path = tmp.name
|
| 59 |
+
print("Sending request to Gemini API...")
|
| 60 |
+
# Add a timeout to prevent indefinite waiting
|
| 61 |
+
start_time = time.time()
|
| 62 |
+
max_wait_time = 60 # Maximum wait time in seconds
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
stream = client.models.generate_content_stream(
|
| 66 |
+
model=model,
|
| 67 |
+
contents=contents,
|
| 68 |
+
config=generate_content_config,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
for chunk in stream:
|
| 72 |
+
# Check for timeout
|
| 73 |
+
if time.time() - start_time > max_wait_time:
|
| 74 |
+
print("Gemini API request timed out after", max_wait_time, "seconds")
|
| 75 |
+
break
|
| 76 |
+
|
| 77 |
+
if not chunk.candidates or not chunk.candidates[0].content or not chunk.candidates[0].content.parts:
|
| 78 |
+
continue
|
| 79 |
+
candidate = chunk.candidates[0].content.parts[0]
|
| 80 |
+
# Check for inline image data
|
| 81 |
+
if candidate.inline_data:
|
| 82 |
+
save_binary_file(temp_path, candidate.inline_data.data)
|
| 83 |
+
print(f"Smile enhancement image generated: {temp_path}")
|
| 84 |
+
image_path = temp_path
|
| 85 |
+
# If an image is found, we assume that is the desired output.
|
| 86 |
+
break
|
| 87 |
+
else:
|
| 88 |
+
# Accumulate text response if no inline_data is present.
|
| 89 |
+
text_response += chunk.text + "\n"
|
| 90 |
+
print("Received text response from Gemini API")
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"Error during content generation: {str(e)}")
|
| 93 |
+
# Continue with the function, returning empty responses
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error in Gemini API setup: {str(e)}")
|
| 96 |
+
return None, f"Error: {str(e)}"
|
| 97 |
+
finally:
|
| 98 |
+
# Always clean up files
|
| 99 |
+
try:
|
| 100 |
+
if 'files' in locals() and files:
|
| 101 |
+
del files
|
| 102 |
+
except:
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
return image_path, text_response
|
| 106 |
+
|
| 107 |
+
def assess_image_quality(original_image, enhanced_image):
|
| 108 |
+
"""
|
| 109 |
+
Assesses the quality of the enhanced image based on specific criteria.
|
| 110 |
+
Returns a tuple of (is_acceptable, feedback_message)
|
| 111 |
+
"""
|
| 112 |
+
try:
|
| 113 |
+
# Check if enhanced image exists
|
| 114 |
+
if enhanced_image is None:
|
| 115 |
+
return False, "No enhanced image generated"
|
| 116 |
+
|
| 117 |
+
# Image dimension checks
|
| 118 |
+
if enhanced_image.size[0] < 100 or enhanced_image.size[1] < 100:
|
| 119 |
+
return False, "Enhanced image appears to be too small or improperly sized"
|
| 120 |
+
|
| 121 |
+
# Check that the enhanced image has similar dimensions to the original
|
| 122 |
+
# This helps ensure facial proportions are maintained
|
| 123 |
+
width_diff = abs(original_image.size[0] - enhanced_image.size[0])
|
| 124 |
+
height_diff = abs(original_image.size[1] - enhanced_image.size[1])
|
| 125 |
+
|
| 126 |
+
# If dimensions are significantly different, it suggests the image proportions changed
|
| 127 |
+
if width_diff > 20 or height_diff > 20:
|
| 128 |
+
return False, "Enhanced image dimensions differ significantly from original, suggesting facial proportions may have changed"
|
| 129 |
+
|
| 130 |
+
# Check image has proper RGB channels for natural skin tones
|
| 131 |
+
if enhanced_image.mode != 'RGB':
|
| 132 |
+
return False, "Enhanced image does not have the correct color mode"
|
| 133 |
+
|
| 134 |
+
# For now, we'll do basic checks and assume the model follows guidelines
|
| 135 |
+
return True, "Image passes quality assessment criteria"
|
| 136 |
+
except Exception as e:
|
| 137 |
+
print(f"Error in quality assessment: {str(e)}")
|
| 138 |
+
# Default to not accepting the image if assessment fails
|
| 139 |
+
return False, f"Assessment error: {str(e)}"
|
| 140 |
+
|
| 141 |
+
def process_smile_enhancement(input_image, max_attempts=2):
|
| 142 |
+
try:
|
| 143 |
+
if input_image is None:
|
| 144 |
+
return None, "", ""
|
| 145 |
+
|
| 146 |
+
# Get API key from environment variable
|
| 147 |
+
gemini_api_key = "AIzaSyCVzRDxkuvtaS1B22F_F-zl0ehhXR0nuU8"
|
| 148 |
+
if not gemini_api_key:
|
| 149 |
+
print("Error: GEMINI_API_KEY not found in environment variables")
|
| 150 |
+
return [input_image], "", "API key not configured"
|
| 151 |
+
|
| 152 |
+
# Save the input image to a temporary file
|
| 153 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 154 |
+
input_path = tmp.name
|
| 155 |
+
input_image.save(input_path)
|
| 156 |
+
print(f"Input image saved to {input_path}")
|
| 157 |
+
|
| 158 |
+
# Initialize attempt counter and result variables
|
| 159 |
+
current_attempt = 0
|
| 160 |
+
result_img = None
|
| 161 |
+
feedback_history = []
|
| 162 |
+
max_processing_time = 120 # Maximum time in seconds for overall processing
|
| 163 |
+
start_processing_time = time.time()
|
| 164 |
+
|
| 165 |
+
while current_attempt < max_attempts:
|
| 166 |
+
# Check if overall processing time exceeded
|
| 167 |
+
if time.time() - start_processing_time > max_processing_time:
|
| 168 |
+
print(f"Overall processing time exceeded {max_processing_time} seconds")
|
| 169 |
+
break
|
| 170 |
+
|
| 171 |
+
current_attempt += 1
|
| 172 |
+
print(f"Starting processing attempt {current_attempt}/{max_attempts}...")
|
| 173 |
+
|
| 174 |
+
# Create a comprehensive prompt for true smile enhancement that affects facial features naturally
|
| 175 |
+
# Adjust prompt based on previous attempts if needed
|
| 176 |
+
prompt = """
|
| 177 |
+
Create a naturally enhanced smile that suits this specific person's face and character. Make the following personalized improvements:
|
| 178 |
+
|
| 179 |
+
- Slightly enhance the existing teeth while PRESERVING their natural color, spacing, and individual characteristics
|
| 180 |
+
- DO NOT make teeth perfectly white or perfectly aligned - keep some natural variation and character
|
| 181 |
+
- Create subtle, natural smile lines around the eyes (crow's feet) appropriate for this person's age and face
|
| 182 |
+
- Slightly raise the cheeks WITHOUT widening the face
|
| 183 |
+
- Add a slight narrowing of the eyes that happens in genuine smiles
|
| 184 |
+
- Create subtle dimples ONLY if they already exist in the original image
|
| 185 |
+
- Enhance the overall joyful expression while maintaining the person's unique facial structure
|
| 186 |
+
|
| 187 |
+
IMPORTANT GUIDELINES:
|
| 188 |
+
- PRESERVE THE PERSON'S NATURAL DENTAL CHARACTERISTICS - teeth should still look like THEIR teeth, just slightly enhanced
|
| 189 |
+
- Keep teeth coloration natural and appropriate for the person - avoid unnaturally white teeth
|
| 190 |
+
- Maintain slight natural imperfections in tooth alignment that give character to the smile
|
| 191 |
+
- Create a genuine, authentic-looking smile that affects the entire face naturally
|
| 192 |
+
- ABSOLUTELY CRITICAL: DO NOT widen the face or change face width at all
|
| 193 |
+
- Preserve the person's identity completely (extremely important)
|
| 194 |
+
- Preserve exact facial proportions and face width of the original image
|
| 195 |
+
- Maintain natural-looking results appropriate for the person's age and face structure
|
| 196 |
+
- Keep teeth proportionate to the face - avoid making them too large or prominent
|
| 197 |
+
- Maintain proper tooth-to-face ratio and ensure teeth fit naturally within the mouth
|
| 198 |
+
- Keep the original background, lighting, and image quality intact
|
| 199 |
+
- Ensure the enhanced smile looks natural, genuine, and believable
|
| 200 |
+
- Create a smile that looks like a moment of true happiness for THIS specific person
|
| 201 |
+
- Remember that not everyone has or wants perfect white teeth - the enhancements should SUIT THE INDIVIDUAL
|
| 202 |
+
- If teeth are enhanced, maintain their natural characteristics while making subtle improvements
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
# If not the first attempt, add previous feedback to the prompt
|
| 206 |
+
if current_attempt > 1 and feedback_history:
|
| 207 |
+
prompt += """
|
| 208 |
+
|
| 209 |
+
IMPORTANT FEEDBACK FROM PREVIOUS ATTEMPT:
|
| 210 |
+
""" + " ".join(feedback_history) + """
|
| 211 |
+
Please address these issues in this new attempt.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
# Process silently
|
| 215 |
+
print(f"Processing attempt {current_attempt}/{max_attempts}...")
|
| 216 |
+
|
| 217 |
+
# Set timeout for individual API call
|
| 218 |
+
api_call_timeout = time.time() + 45 # 45 second timeout for API call
|
| 219 |
+
|
| 220 |
+
try:
|
| 221 |
+
# Process the image using Google's Gemini model with timeout
|
| 222 |
+
image_path, text_response = generate(text=prompt, file_name=input_path, api_key=gemini_api_key)
|
| 223 |
+
|
| 224 |
+
# Check if API call timeout occurred
|
| 225 |
+
if time.time() > api_call_timeout:
|
| 226 |
+
print("API call timeout occurred")
|
| 227 |
+
feedback_history.append("API call timed out, trying again with simplified request.")
|
| 228 |
+
continue
|
| 229 |
+
|
| 230 |
+
print(f"API response received: Image path: {image_path is not None}, Text length: {len(text_response)}")
|
| 231 |
+
|
| 232 |
+
if image_path:
|
| 233 |
+
# Load and convert the image if needed
|
| 234 |
+
try:
|
| 235 |
+
result_img = Image.open(image_path)
|
| 236 |
+
if result_img.mode == "RGBA":
|
| 237 |
+
result_img = result_img.convert("RGB")
|
| 238 |
+
|
| 239 |
+
print("Successfully loaded generated image")
|
| 240 |
+
|
| 241 |
+
# Assess the quality of the enhanced image
|
| 242 |
+
is_acceptable, assessment_feedback = assess_image_quality(input_image, result_img)
|
| 243 |
+
print(f"Image quality assessment: {is_acceptable}, {assessment_feedback}")
|
| 244 |
+
|
| 245 |
+
if is_acceptable:
|
| 246 |
+
# Return the enhanced image with success message
|
| 247 |
+
success_message = "Successfully loaded generated image\nImage quality assessment: True, Image passes quality assessment criteria"
|
| 248 |
+
return [result_img], "", success_message
|
| 249 |
+
else:
|
| 250 |
+
# Image didn't pass quality assessment, add feedback for next attempt
|
| 251 |
+
feedback_history.append(assessment_feedback)
|
| 252 |
+
|
| 253 |
+
# If we've reached max attempts, return the best result so far
|
| 254 |
+
if current_attempt >= max_attempts:
|
| 255 |
+
print("Max attempts reached, returning best result")
|
| 256 |
+
return [result_img], "", ""
|
| 257 |
+
except Exception as img_error:
|
| 258 |
+
print(f"Error processing the generated image: {str(img_error)}")
|
| 259 |
+
feedback_history.append(f"Error with image: {str(img_error)}")
|
| 260 |
+
else:
|
| 261 |
+
# No image was generated, only text response
|
| 262 |
+
print("No image was generated, only text response")
|
| 263 |
+
feedback_history.append("No image was generated in the previous attempt.")
|
| 264 |
+
|
| 265 |
+
# If we've reached max attempts, return the original image
|
| 266 |
+
if current_attempt >= max_attempts:
|
| 267 |
+
print("Max attempts reached, returning original image")
|
| 268 |
+
return [input_image], "", ""
|
| 269 |
+
except Exception as gen_error:
|
| 270 |
+
print(f"Error during generation attempt {current_attempt}: {str(gen_error)}")
|
| 271 |
+
feedback_history.append(f"Error during processing: {str(gen_error)}")
|
| 272 |
+
|
| 273 |
+
# If we've reached max attempts, return the original image
|
| 274 |
+
if current_attempt >= max_attempts:
|
| 275 |
+
return [input_image], "", ""
|
| 276 |
+
|
| 277 |
+
# Return the original image as a fallback without messages
|
| 278 |
+
print("Returning original image as fallback")
|
| 279 |
+
return [input_image], "", ""
|
| 280 |
+
except Exception as e:
|
| 281 |
+
# Return the original image silently on error
|
| 282 |
+
print(f"Overall error in process_smile_enhancement: {str(e)}")
|
| 283 |
+
return [input_image], "", ""
|
| 284 |
+
|
| 285 |
+
# Create a clean interface with minimal UI elements and no settings/deployment info
|
| 286 |
+
with gr.Blocks(title="Smile Enhancement", css="footer {visibility: hidden} .gradio-container {min-height: 0 !important}") as demo:
|
| 287 |
+
with gr.Row():
|
| 288 |
+
with gr.Column():
|
| 289 |
+
image_input = gr.Image(
|
| 290 |
+
type="pil",
|
| 291 |
+
label=None,
|
| 292 |
+
image_mode="RGB",
|
| 293 |
+
elem_classes="upload-box"
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
submit_btn = gr.Button("Enhance Smile with Natural Expressions", elem_classes="generate-btn")
|
| 297 |
+
|
| 298 |
+
with gr.Column():
|
| 299 |
+
output_gallery = gr.Gallery(label=None)
|
| 300 |
+
|
| 301 |
+
# Simplify feedback to minimize UI elements
|
| 302 |
+
feedback_text = gr.Textbox(label=None, visible=True, elem_classes="status-box")
|
| 303 |
+
|
| 304 |
+
# Hidden element for structure
|
| 305 |
+
output_text = gr.Textbox(visible=False)
|
| 306 |
+
|
| 307 |
+
submit_btn.click(
|
| 308 |
+
fn=process_smile_enhancement,
|
| 309 |
+
inputs=[image_input],
|
| 310 |
+
outputs=[output_gallery, output_text, feedback_text]
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
# Launch the app without showing Gradio branding or share links
|
| 314 |
+
demo.queue(max_size=50).launch(show_api=False, show_error=False)
|
data/1.jpg
ADDED
|
Git LFS Details
|
data/1.webp
ADDED
|
data/1777043.jpg
ADDED
|
Git LFS Details
|
data/2.webp
ADDED
|
data/2807615.jpg
ADDED
|
Git LFS Details
|
data/3.webp
ADDED
|
data/76860.jpg
ADDED
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
google-genai
|
| 2 |
+
gradio
|
| 3 |
+
pydantic
|
| 4 |
+
python-dotenv
|