File size: 8,053 Bytes
c55fe6a
583b7ad
c55fe6a
 
 
 
c16bc85
c55fe6a
 
 
 
 
583b7ad
 
c55fe6a
 
 
 
d50deb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c55fe6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6962136
 
ad3aed5
6962136
 
 
 
 
 
 
 
 
 
ad3aed5
6962136
 
 
 
 
 
 
 
9e6acd9
 
 
 
6962136
 
 
c55fe6a
6962136
c55fe6a
6962136
c55fe6a
6962136
ad3aed5
c55fe6a
 
 
 
 
 
6962136
 
 
 
 
c55fe6a
6962136
c55fe6a
 
 
 
6962136
c55fe6a
 
 
ad3aed5
6962136
583b7ad
c55fe6a
6962136
ad3aed5
c55fe6a
 
 
 
 
 
 
 
 
 
 
 
6962136
 
c55fe6a
 
 
6962136
c55fe6a
 
 
 
 
 
 
 
6962136
 
 
 
 
c55fe6a
 
 
 
 
 
abc4f31
c55fe6a
 
 
 
6962136
c55fe6a
 
 
 
6962136
c55fe6a
 
6962136
c55fe6a
 
d50deb1
c55fe6a
6962136
c55fe6a
 
9e6acd9
c55fe6a
 
 
d50deb1
c55fe6a
9e6acd9
c55fe6a
 
 
6962136
c55fe6a
 
6962136
c55fe6a
 
 
6962136
 
c55fe6a
 
9e6acd9
 
 
 
 
 
 
 
 
 
d50deb1
 
 
 
 
 
 
c55fe6a
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import gradio as gr
from src.agents.image_edit_agent import image_edit_agent, ImageEditDeps, EditImageResult
import os
from src.hopter.client import Hopter, Environment
from src.services.generate_mask import GenerateMaskService
from dotenv import load_dotenv
from src.utils import upload_image
from pydantic_ai.messages import (
    ToolCallPart,
    ToolReturnPart
)
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel(    
    "gpt-4o",
    api_key=os.environ.get("OPENAI_API_KEY"),
)

INTRO = """
# Image Editing Assistant

### Experience seamless image editing using natural language in a chat-based interface.

With this demo, you can:
- Enhance or upscale an image
- Remove objects from an image
- Replace elements within an image
- Change the background
"""

EXAMPLES = [
    {
        "text": "Replace the background to the space with stars and planets",
        "files": [
            "https://cdn.prod.website-files.com/66f230993926deadc0ac3a44/66f370d65f158cbbcfbcc532_Crossed%20Arms%20Levi%20Meir%20Clancy.jpg"
        ]
    },
    {
        "text": "Change all the balloons to red in the image",
        "files": [
            "https://www.apple.com/tv-pr/articles/2024/10/apple-tv-unveils-severance-season-two-teaser-ahead-of-the-highly-anticipated-return-of-the-emmy-and-peabody-award-winning-phenomenon/images/big-image/big-image-01/1023024_Severance_Season_Two_Official_Trailer_Big_Image_01_big_image_post.jpg.large_2x.jpg"
        ]
    },
    {
        "text": "Change coffee to a glass of water",
        "files": [
            "https://previews.123rf.com/images/vadymvdrobot/vadymvdrobot1812/vadymvdrobot181201149/113217373-image-of-smiling-woman-holding-takeaway-coffee-in-paper-cup-and-taking-selfie-while-walking-through.jpg"
        ]
    },
    {
        "text": "ENHANCE!",
        "files": [
            "https://m.media-amazon.com/images/M/MV5BNzM3ODc5NzEtNzJkOC00MDM4LWI0MTYtZTkyNmY3ZTBhYzkxXkEyXkFqcGc@._V1_QL75_UX1000_CR0,52,1000,563_.jpg"
        ]
    }
]

load_dotenv()

def build_user_message(chat_input):
    text = chat_input["text"]
    images = chat_input["files"]
    messages = [
        {
            "role": "user",
            "content": text
        }
    ]
    if images:
        messages.extend([
            {
                "role": "user",
                "content": {"path": image}
            }
            for image in images
        ])
    return messages

def build_messages_for_agent(chat_input, past_messages):
    # filter out image messages from past messages to save on tokens
    messages = past_messages
    
    # add the user's text message
    if chat_input["text"]:
        messages.append({
            "type": "text",
            "text": chat_input["text"]
        })

    # add the user's image message
    files = chat_input.get("files", [])
    image_url = upload_image(files[0]) if files else None
    if image_url:
        messages.append({
            "type": "image_url",
            "image_url": {"url": image_url}
        })

    return messages
    
def select_example(x: gr.SelectData, chat_input):
    chat_input["text"] = x.value["text"]
    chat_input["files"] = x.value["files"]
    return chat_input

async def stream_from_agent(chat_input, chatbot, past_messages, current_image):
    # Prepare messages for the UI
    chatbot.extend(build_user_message(chat_input))
    yield {"text": "", "files": []}, chatbot, gr.skip, gr.skip()

    # Prepare messages for the agent
    text = chat_input["text"]
    files = chat_input.get("files", [])
    image_url = upload_image(files[0]) if files else None
    messages = [
        {
            "type": "text",
            "text": text
        },
    ]
    if image_url:
        messages.append(
            {"type": "image_url", "image_url": {"url": image_url}}
        )
        current_image = image_url

    # Dependencies
    hopter = Hopter(os.environ.get("HOPTER_API_KEY"), environment=Environment.STAGING)
    mask_service = GenerateMaskService(hopter=hopter)
    deps = ImageEditDeps(
        edit_instruction=text,
        image_url=current_image,
        hopter_client=hopter,
        mask_service=mask_service
    )

    # Run the agent
    async with image_edit_agent.run_stream(
        messages,
        deps=deps,
        message_history=past_messages
    ) as result:
        for message in result.new_messages():
            for call in message.parts:
                if isinstance(call, ToolCallPart):
                    call_args = (
                        call.args.args_json
                        if hasattr(call.args, 'args_json')
                        else call.args
                    )
                    metadata = {
                        'title': f'🛠️ Using {call.tool_name}',
                    }
                    # set the tool call id so that when the tool returns
                    # we can find this message and update with the result
                    if call.tool_call_id is not None:
                        metadata['id'] = call.tool_call_id

                    # Create a tool call message to show on the UI
                    gr_message = {
                        'role': 'assistant',
                        'content': 'Parameters: ' + call_args,
                        'metadata': metadata,
                    }
                    chatbot.append(gr_message)
                if isinstance(call, ToolReturnPart):
                    for gr_message in chatbot:
                        # Skip messages without metadata
                        if not gr_message.get('metadata'):
                            continue

                        if gr_message['metadata'].get('id', '') == call.tool_call_id:
                            if isinstance(call.content, EditImageResult):
                                chatbot.append({
                                    "role": "assistant",
                                    "content": gr.Image(call.content.edited_image_url),
                                    "files": [call.content.edited_image_url]
                                })
                                current_image = call.content.edited_image_url
                            else:
                                gr_message['content'] += (
                                    f'\nOutput: {call.content}'
                                )
                yield gr.skip(), chatbot, gr.skip(), gr.skip()

        chatbot.append({'role': 'assistant', 'content': ''})
        async for message in result.stream_text():
            chatbot[-1]['content'] = message
            yield gr.skip(), chatbot, gr.skip(), gr.skip()
        past_messages = result.all_messages()

        yield gr.Textbox(interactive=True), gr.skip(), past_messages, current_image

with gr.Blocks() as demo:
    gr.Markdown(INTRO)

    current_image = gr.State(None)
    past_messages = gr.State([])
    chatbot = gr.Chatbot(
        elem_id="chatbot",
        label='Image Editing Assistant',
        type='messages',
        avatar_images=(None, 'https://ai.pydantic.dev/img/logo-white.svg'),
        examples=EXAMPLES
    )

    with gr.Row():
        chat_input = gr.MultimodalTextbox(
            interactive=True,
            file_count="single",
            show_label=False,
            placeholder='How would you like to edit this image?',
            sources=["upload"]
        )
    generation = chat_input.submit(
        stream_from_agent,
        inputs=[chat_input, chatbot, past_messages, current_image],
        outputs=[chat_input, chatbot, past_messages, current_image],
    )

    chatbot.example_select(
        select_example,
        inputs=[chat_input],
        outputs=[chat_input],
    ).then(
        stream_from_agent,
        inputs=[chat_input, chatbot, past_messages, current_image],
        outputs=[chat_input, chatbot, past_messages, current_image],
    )

    examples = gr.Examples(
        examples=EXAMPLES,
        inputs=[chat_input],
        outputs=[chat_input],
    )
    

if __name__ == '__main__':
    demo.launch()