File size: 7,741 Bytes
5b11622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import base64
from openai import OpenAI
from dotenv import load_dotenv
import fal_client
import os
from datetime import datetime
import requests
import gradio as gr

load_dotenv()

client = OpenAI()

# Function to encode the image
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

def generate_description(image):
    """Generate description for uploaded image using OpenAI vision"""
    if image is None:
        return "Please upload an image first."
    
    try:
        # Convert PIL image to base64
        import io
        buffered = io.BytesIO()
        image.save(buffered, format="JPEG")
        base64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
        
        response = client.responses.create(
            model="gpt-4.1",
            input=[
                {
                    "role": "user",
                    "content": [
                        { "type": "input_text", "text": "Describe the image in rich, natural detail for txt2img model. Focus on the scene, the person, their casual clothes, accessories, makeup, the everyday environment, and what they're doing. Capture the emotions, expressions, mood, and candid vibe as if it were a real Instagram Reel, TikTok, or Pinterest-style snapshot. Mention the camera angle, framing, depth of field, shadows, colors, and textures in a way that feels spontaneous and unpolished, with natural light and subtle motion blur. Convey the overall feeling, atmosphere, and sense of being in that moment. Describe the angle of the camera and pose of the model precisely. The result will be used to generate a similar image with a txt2img model, emphasizing realism, casualness, and lived-in authenticity rather than studio-perfect or commercialized style. Highlight the photo taken with iPhone front camera in-the-moment." },
                        {
                            "type": "input_image",
                            "image_url": f"data:image/jpeg;base64,{base64_image}",
                        },
                    ],
                }
            ],
        )
        
        description = response.output_text + "\n Photo taken with iPhone front camera in-the-moment."
        return description
        
    except Exception as e:
        return f"Error generating description: {str(e)}"


model = "fal-ai/gemini-25-flash-image" # , "fal-ai/nano-banana",  

def on_queue_update(update):
    if isinstance(update, fal_client.InProgress):
        for log in update.logs:
           print(log["message"])

def generate_avatar(prompt, selected_model):
    """Generate avatar image with given prompt and selected model"""
    if not prompt or prompt.strip() == "":
        return None, "Please provide a prompt for avatar generation."
    
    try:
        result = fal_client.subscribe(
            selected_model,
            arguments={
                "prompt": prompt,
                "num_images": 1,
                "output_format": "png"
            },
            with_logs=True,
            on_queue_update=on_queue_update,
        )

        # Return the first generated image
        if 'images' in result and len(result['images']) > 0:
            image_url = result['images'][0]['url']
            
            # Download the image
            response = requests.get(image_url)
            if response.status_code == 200:
                # Convert to PIL Image for Gradio display
                from PIL import Image
                import io
                image = Image.open(io.BytesIO(response.content))
                return image, "Avatar generated successfully!"
            else:
                return None, f"Failed to download image: {response.status_code}"
        else:
            return None, "No images found in result"
            
    except Exception as e:
        return None, f"Error generating avatar: {str(e)}"

# Gradio Interface
def process_image_and_generate_avatar(image):
    """Process uploaded image and generate avatar"""
    if image is None:
        return None, "Please upload an image first.", "Upload an image to get started!"
    
    # Generate description
    description = generate_description(image)
    
    # Generate avatar
    avatar_image, message = generate_avatar(description)
    
    return avatar_image, description, message

# Available models
available_models = [
    "fal-ai/gemini-25-flash-image",
    "fal-ai/nano-banana", 
    "fal-ai/flux-pro",
    "fal-ai/stable-diffusion-v35-large",
    "fal-ai/qwen-image",
    "fal-ai/imagen4-preview",
    "fal-ai/imagen4-preview-fast",
    "fal-ai/imagen4-preview-ultra"
]

# Create Gradio interface
with gr.Blocks(title="Avatar Clone Generator") as demo:
    gr.Markdown("# Avatar Clone Generator")
    gr.Markdown("Upload a photo to generate a description and create an avatar!")
    
    with gr.Row():
        with gr.Column():
            # Image upload
            input_image = gr.Image(
                label="Upload Photo",
                type="pil",
                height=300
            )
            
            # Model selection
            model_dropdown = gr.Dropdown(
                choices=available_models,
                value="fal-ai/gemini-25-flash-image",
                label="Select Vision Model",
                info="Choose the AI model for generating your avatar"
            )
            
            # Generate description button
            generate_desc_btn = gr.Button("Generate Description", variant="primary")
            
            # Description text area (editable)
            description_text = gr.Textbox(
                label="Generated Description (You can edit this)",
                lines=8,
                placeholder="Description will appear here after uploading an image..."
            )
            
            # Generate avatar button
            generate_avatar_btn = gr.Button("Generate Avatar", variant="secondary")
            
            # Status message
            status_text = gr.Textbox(
                label="Status",
                lines=2,
                interactive=False
            )
        
        with gr.Column():
            # Generated avatar display
            output_image = gr.Image(
                label="Generated Avatar",
                height=400
            )
    
    # Event handlers
    def on_image_upload(image):
        if image is not None:
            description = generate_description(image)
            return description, "Image uploaded! Click 'Generate Description' to proceed."
        return "", "Please upload an image."
    
    def on_generate_description(image):
        if image is None:
            return "", "Please upload an image first."
        description = generate_description(image)
        return description, "Description generated! You can edit it if needed."
    
    def on_generate_avatar(description, selected_model):
        if not description or description.strip() == "":
            return None, "Please generate a description first."
        avatar_image, message = generate_avatar(description, selected_model)
        return avatar_image, message
    
    # Connect events
    input_image.change(
        fn=on_image_upload,
        inputs=[input_image],
        outputs=[description_text, status_text]
    )
    
    generate_desc_btn.click(
        fn=on_generate_description,
        inputs=[input_image],
        outputs=[description_text, status_text]
    )
    
    generate_avatar_btn.click(
        fn=on_generate_avatar,
        inputs=[description_text, model_dropdown],
        outputs=[output_image, status_text]
    )

if __name__ == "__main__":
    demo.launch(share=True)