AMfeta99 commited on
Commit
4bdfa75
·
verified ·
1 Parent(s): f003f38

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -133
app.py CHANGED
@@ -1,19 +1,32 @@
1
  from huggingface_hub import InferenceClient
2
- from langchain_community.llms import HuggingFaceHub
3
  from langchain_community.tools import DuckDuckGoSearchResults
4
- from langchain.agents import create_react_agent
5
- from langchain.tools import BaseTool
 
6
  from PIL import Image, ImageDraw, ImageFont
7
  import tempfile
8
  import gradio as gr
9
- import requests
10
  from io import BytesIO
 
11
 
12
- # Your HF API token here (set your actual token)
13
- #HF_TOKEN
14
 
15
- #%% Methods
 
 
 
 
 
 
 
 
 
 
 
 
16
 
 
 
17
  def add_label_to_image(image, label):
18
  draw = ImageDraw.Draw(image)
19
  font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
@@ -22,164 +35,77 @@ def add_label_to_image(image, label):
22
  font = ImageFont.truetype(font_path, font_size)
23
  except:
24
  font = ImageFont.load_default()
25
- text_bbox = draw.textbbox((0, 0), label, font=font)
26
- text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
27
  position = (image.width - text_width - 20, image.height - text_height - 20)
28
- rect_margin = 10
29
- rect_position = [
30
- position[0] - rect_margin,
31
- position[1] - rect_margin,
32
- position[0] + text_width + rect_margin,
33
- position[1] + text_height + rect_margin,
34
- ]
35
  draw.rectangle(rect_position, fill=(0, 0, 0, 128))
36
  draw.text(position, label, fill="white", font=font)
37
  return image
38
 
39
 
40
- def plot_and_save_agent_image(agent_image, label, save_path=None):
41
- # agent_image is a PIL Image already in this refactor
42
- pil_image = agent_image
43
-
44
- labeled_image = add_label_to_image(pil_image, label)
45
- labeled_image.show()
46
-
47
- if save_path:
48
- labeled_image.save(save_path)
49
- print(f"Image saved to {save_path}")
50
- else:
51
- print("No save path provided. Image not saved.")
52
-
53
-
54
  def generate_prompts_for_object(object_name):
55
  return {
56
  "past": f"Show an old version of a {object_name} from its early days.",
57
  "present": f"Show a {object_name} with current features/design/technology.",
58
- "future": f"Show a futuristic version of a {object_name}, by predicting advanced features and futuristic design."
59
- }
60
-
61
-
62
- def generate_object_history(object_name):
63
- images = []
64
- prompts = generate_prompts_for_object(object_name)
65
- labels = {
66
- "past": f"{object_name} - Past",
67
- "present": f"{object_name} - Present",
68
- "future": f"{object_name} - Future"
69
  }
70
 
71
- for time_period, prompt in prompts.items():
72
- print(f"Generating {time_period} frame: {prompt}")
73
- result = agent.invoke(prompt) # returns PIL Image or string output
74
-
75
- # result is a PIL Image from our tool, or fallback string - ensure PIL Image
76
- if isinstance(result, Image.Image):
77
- images.append(result)
78
- image_filename = f"{object_name}_{time_period}.png"
79
- plot_and_save_agent_image(result, labels[time_period], save_path=image_filename)
80
- else:
81
- print(f"Unexpected output for {time_period}: {result}")
82
 
83
- gif_path = f"{object_name}_evolution.gif"
84
- if images:
85
- images[0].save(
86
- gif_path,
87
- save_all=True,
88
- append_images=images[1:],
89
- duration=1000,
90
- loop=0
91
- )
92
- print(f"GIF saved to {gif_path}")
93
- else:
94
- print("No images generated, GIF not created.")
95
-
96
- return images, gif_path
97
-
98
-
99
- #%% Initialization of tools and AI_Agent
100
-
101
- # Initialize HuggingFace Inference Client for text-to-image
102
  text_to_image_client = InferenceClient("m-ric/text-to-image")
103
 
104
- def run_text_to_image(prompt: str) -> Image.Image:
105
- outputs = text_to_image_client.text_to_image(prompt)
106
- # Assuming outputs returns a list of URLs
107
- image_url = outputs[0] if outputs else None
108
- if image_url is None:
109
- raise ValueError("No image URL returned from the model.")
110
- response = requests.get(image_url)
111
- img = Image.open(BytesIO(response.content)).convert("RGB")
112
- return img
113
-
114
- # Custom LangChain tool wrapper for text-to-image
115
- class TextToImageTool(BaseTool):
116
- name = "text-to-image"
117
- description = "Generates an image from a prompt using HuggingFace model"
118
-
119
- def _run(self, prompt: str):
120
- return run_text_to_image(prompt)
121
 
122
- async def _arun(self, prompt: str):
123
- raise NotImplementedError()
124
-
125
- image_generation_tool = TextToImageTool()
126
-
127
- # DuckDuckGo Search Tool from LangChain
128
  search_tool = DuckDuckGoSearchResults()
129
 
130
- # HuggingFace LLM for Qwen2.5
131
- llm_engine = HuggingFaceHub(
132
  repo_id="Qwen/Qwen2.5-72B-Instruct",
133
- huggingfacehub_api_token=HF_TOKEN,
134
- model_kwargs={"temperature": 0.7}
135
  )
136
 
137
- # Create agent with the tools and LLM
138
- agent = create_react_agent(llm_engine, tools=[image_generation_tool, search_tool])
139
 
140
 
141
- #%% Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  def create_gradio_interface():
143
  with gr.Blocks() as demo:
144
- gr.Markdown("# TimeMetamorphy: an object Evolution Generator")
145
-
146
- gr.Markdown("""
147
- ## Unlocking the secrets of time!
148
- This app unveils these mysteries by offering a unique/magic lens that allows us "time travel".
149
- Powered by AI agents equipped with cutting-edge tools, it provides the superpower to explore the past, witness the present, and dream up the future like never before.
150
-
151
- This system allows you to generate visualizations of how an object/concept, like a bicycle or a car, may have evolved over time.
152
- It generates images of the object in the past, present, and future based on your input.
153
-
154
- ### Default Example: Evolution of a Car
155
- Below, you can see a precomputed example of a "car" evolution. Enter another object to generate its evolution.
156
- """)
157
-
158
- default_images = [
159
- ("car_past.png", "Car - Past"),
160
- ("car_present.png", "Car - Present"),
161
- ("car_future.png", "Car - Future")
162
- ]
163
- default_gif_path = "car_evolution.gif"
164
 
165
  with gr.Row():
166
  with gr.Column():
167
- object_name_input = gr.Textbox(
168
- label="Enter an object name (e.g., bicycle, phone)",
169
- placeholder="Enter an object name",
170
- lines=1
171
- )
172
  generate_button = gr.Button("Generate Evolution")
173
- image_gallery = gr.Gallery(
174
- label="Generated Images", show_label=True, columns=3, rows=1, value=default_images
175
- )
176
- gif_output = gr.Image(label="Generated GIF", show_label=True, value=default_gif_path)
177
 
178
- generate_button.click(fn=generate_object_history, inputs=[object_name_input], outputs=[image_gallery, gif_output])
179
-
180
  return demo
181
 
182
 
183
- # Launch the Gradio app
184
  demo = create_gradio_interface()
185
  demo.launch(share=True)
 
1
  from huggingface_hub import InferenceClient
2
+ from langchain_community.llms import HuggingFaceHub
3
  from langchain_community.tools import DuckDuckGoSearchResults
4
+ from langchain.agents import create_react_agent, AgentExecutor
5
+ from langchain_core.tools import BaseTool
6
+ from pydantic import Field
7
  from PIL import Image, ImageDraw, ImageFont
8
  import tempfile
9
  import gradio as gr
 
10
  from io import BytesIO
11
+ from typing import Optional
12
 
 
 
13
 
14
+ # === Image generation tool ===
15
+ class TextToImageTool(BaseTool):
16
+ name: str = "text_to_image"
17
+ description: str = "Generate an image from a text prompt."
18
+ client: InferenceClient = Field(exclude=True)
19
+
20
+ def _run(self, prompt: str) -> Image.Image:
21
+ print(f"[Tool] Generating image for prompt: {prompt}")
22
+ image_bytes = self.client.text_to_image(prompt)
23
+ return Image.open(BytesIO(image_bytes))
24
+
25
+ def _arun(self, prompt: str):
26
+ raise NotImplementedError("This tool does not support async.")
27
 
28
+
29
+ # === Labeling Function ===
30
  def add_label_to_image(image, label):
31
  draw = ImageDraw.Draw(image)
32
  font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
 
35
  font = ImageFont.truetype(font_path, font_size)
36
  except:
37
  font = ImageFont.load_default()
38
+ text_width, text_height = draw.textsize(label, font=font)
 
39
  position = (image.width - text_width - 20, image.height - text_height - 20)
40
+ rect_position = [position[0] - 10, position[1] - 10, position[0] + text_width + 10, position[1] + text_height + 10]
 
 
 
 
 
 
41
  draw.rectangle(rect_position, fill=(0, 0, 0, 128))
42
  draw.text(position, label, fill="white", font=font)
43
  return image
44
 
45
 
46
+ # === Prompt Generator ===
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  def generate_prompts_for_object(object_name):
48
  return {
49
  "past": f"Show an old version of a {object_name} from its early days.",
50
  "present": f"Show a {object_name} with current features/design/technology.",
51
+ "future": f"Show a futuristic version of a {object_name}, predicting future features/designs.",
 
 
 
 
 
 
 
 
 
 
52
  }
53
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # === Agent Setup ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  text_to_image_client = InferenceClient("m-ric/text-to-image")
57
 
58
+ text_to_image_tool = TextToImageTool(client=text_to_image_client)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
 
 
 
 
 
 
60
  search_tool = DuckDuckGoSearchResults()
61
 
62
+ llm = HuggingFaceHub(
 
63
  repo_id="Qwen/Qwen2.5-72B-Instruct",
64
+ model_kwargs={"temperature": 0.7, "max_new_tokens": 512},
 
65
  )
66
 
67
+ agent = create_react_agent(llm=llm, tools=[text_to_image_tool, search_tool])
68
+ agent_executor = AgentExecutor(agent=agent, tools=[text_to_image_tool, search_tool], verbose=True)
69
 
70
 
71
+ # === History Generator ===
72
+ def generate_object_history(object_name: str):
73
+ prompts = generate_prompts_for_object(object_name)
74
+ images = []
75
+ labels = {
76
+ "past": f"{object_name} - Past",
77
+ "present": f"{object_name} - Present",
78
+ "future": f"{object_name} - Future"
79
+ }
80
+ for period, prompt in prompts.items():
81
+ result = text_to_image_tool._run(prompt)
82
+ labeled = add_label_to_image(result, labels[period])
83
+ file_path = f"{object_name}_{period}.png"
84
+ labeled.save(file_path)
85
+ images.append((file_path, labels[period]))
86
+ gif_path = f"{object_name}_evolution.gif"
87
+ pil_images = [Image.open(img[0]) for img in images]
88
+ pil_images[0].save(gif_path, save_all=True, append_images=pil_images[1:], duration=1000, loop=0)
89
+ return images, gif_path
90
+
91
+
92
+ # === Gradio UI ===
93
  def create_gradio_interface():
94
  with gr.Blocks() as demo:
95
+ gr.Markdown("# TimeMetamorphy: Evolution Visualizer")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  with gr.Row():
98
  with gr.Column():
99
+ object_input = gr.Textbox(label="Enter Object (e.g., car, phone)")
 
 
 
 
100
  generate_button = gr.Button("Generate Evolution")
101
+ gallery = gr.Gallery(label="Generated Images").style(grid=3)
102
+ gif_display = gr.Image(label="Generated GIF")
103
+
104
+ generate_button.click(fn=generate_object_history, inputs=object_input, outputs=[gallery, gif_display])
105
 
 
 
106
  return demo
107
 
108
 
109
+ # === Launch App ===
110
  demo = create_gradio_interface()
111
  demo.launch(share=True)