Saumith commited on
Commit
f77f9ee
·
verified ·
1 Parent(s): 5a504a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -37
app.py CHANGED
@@ -18,21 +18,21 @@ from mosaic_generator.mosaic_builder import MosaicBuilder
18
  from mosaic_generator.metrics import mse, ssim_rgb
19
 
20
 
21
- # -------------------------------------------------------------------
22
- # GLOBAL TILE MANAGER loaded ONCE for the entire Space
23
- # -------------------------------------------------------------------
24
  TM = TileManager()
25
  TM.load(sample_size=20000)
26
 
27
 
28
- # -------------------------------------------------------------------
29
  # MAIN PIPELINE
30
- # -------------------------------------------------------------------
31
  def run_pipeline(
32
  img, grid_size, tile_px, tile_sample,
33
  quantize_on, quantize_colors, show_grid
34
  ):
35
- """Full end-to-end mosaic generation pipeline."""
36
 
37
  if img is None:
38
  return None, None, None, "Upload an image first."
@@ -40,10 +40,10 @@ def run_pipeline(
40
  img_np = np.array(img.convert("RGB"))
41
  grid_n = int(grid_size)
42
 
43
- # Crop
44
  base = crop_to_multiple(img_np, grid_n)
45
 
46
- # Optional quantization
47
  if quantize_on:
48
  try:
49
  q = Image.fromarray(base).quantize(
@@ -55,7 +55,7 @@ def run_pipeline(
55
  except Exception as e:
56
  return None, None, None, f"Quantization failed: {e}"
57
 
58
- # Compute LAB means
59
  try:
60
  t0 = time.perf_counter()
61
  cell_means, dims = compute_cell_means_lab(base, grid_n)
@@ -65,16 +65,16 @@ def run_pipeline(
65
 
66
  w, h, cell_w, cell_h = dims
67
 
68
- # Prepare tiles
69
  TM.prepare_scaled_tiles(cell_w, cell_h)
70
 
71
- # FAISS lookup
72
  try:
73
  idxs = TM.lookup_tiles(cell_means)
74
  except Exception as e:
75
  return None, None, None, f"Tile lookup failed: {e}"
76
 
77
- # Mosaic build
78
  builder = MosaicBuilder(TM)
79
  try:
80
  mosaic_np = builder.build(idxs, dims, grid_n)
@@ -83,14 +83,14 @@ def run_pipeline(
83
 
84
  t2 = time.perf_counter()
85
 
86
- # Metrics
87
  try:
88
  mse_val = mse(base, mosaic_np)
89
  ssim_val = ssim_rgb(base, mosaic_np)
90
- except:
91
  mse_val, ssim_val = -1, -1
92
 
93
- # Grid overlay
94
  segmented = Image.fromarray(base)
95
  if show_grid:
96
  seg = segmented.copy()
@@ -101,7 +101,7 @@ def run_pipeline(
101
  draw.line([(0, y), (w, y)], fill="red", width=1)
102
  segmented = seg
103
 
104
- # Text report
105
  report = (
106
  f"MSE: {mse_val:.2f}\n"
107
  f"SSIM: {ssim_val:.4f}\n\n"
@@ -118,26 +118,32 @@ def run_pipeline(
118
  )
119
 
120
 
121
- # -------------------------------------------------------------------
122
  # GRADIO UI
123
- # -------------------------------------------------------------------
124
  def build_demo():
125
  with gr.Blocks(title="High-Performance Mosaic Generator") as demo:
126
 
127
  gr.Markdown("# ⚡ High-Performance Mosaic Generator (Lab 5)")
128
- gr.Markdown("FAISS-accelerated mosaic generation • 20×–100× faster than Lab 1.\n")
129
 
130
  with gr.Row():
131
 
132
- # ------------------------------------------------
133
- # LEFT — Inputs
134
- # ------------------------------------------------
135
  with gr.Column(scale=1):
136
 
137
  img_in = gr.Image(type="pil", label="Upload Image")
138
 
139
- grid_size = gr.Radio(["16", "32", "64", "128"], value="32", label="Grid Size")
140
- tile_px = gr.Radio(["8", "16", "24", "32"], value="16", label="Tile Resolution (px)")
 
 
 
 
 
 
 
 
141
 
142
  tile_sample = gr.Slider(
143
  512, 20000, step=256, value=2048,
@@ -154,26 +160,23 @@ def build_demo():
154
 
155
  run_btn = gr.Button("Generate Mosaic", variant="primary")
156
 
157
- # ------------------------------------------------
158
- # EXAMPLE IMAGES (URL-based HF compatible)
159
- # ------------------------------------------------
160
- gr.Markdown("### Example Images")
161
 
162
  example_urls = [
163
- ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio/image_classifier/squirrel.jpg"],
164
- ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio/image_classifier/cat.jpg"],
165
- ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio/image_classifier/cheetah.jpg"],
166
  ]
167
 
168
  gr.Examples(
169
  examples=example_urls,
170
  inputs=[img_in],
 
171
  cache_examples=False
172
  )
173
 
174
- # ------------------------------------------------
175
- # RIGHT — Outputs
176
- # ------------------------------------------------
177
  with gr.Column(scale=2):
178
 
179
  with gr.Tab("Original"):
@@ -187,7 +190,7 @@ def build_demo():
187
 
188
  report = gr.Textbox(label="Timing & Metrics", lines=10)
189
 
190
- # Connect Generate button
191
  run_btn.click(
192
  fn=run_pipeline,
193
  inputs=[img_in, grid_size, tile_px, tile_sample,
@@ -198,9 +201,9 @@ def build_demo():
198
  return demo
199
 
200
 
201
- # -------------------------------------------------------------------
202
  # LAUNCH
203
- # -------------------------------------------------------------------
204
  if __name__ == "__main__":
205
  demo = build_demo()
206
  demo.launch()
 
18
  from mosaic_generator.metrics import mse, ssim_rgb
19
 
20
 
21
+ # ---------------------------------------------------------
22
+ # GLOBAL TILE MANAGER Loaded ONCE when the Space starts
23
+ # ---------------------------------------------------------
24
  TM = TileManager()
25
  TM.load(sample_size=20000)
26
 
27
 
28
+ # ---------------------------------------------------------
29
  # MAIN PIPELINE
30
+ # ---------------------------------------------------------
31
  def run_pipeline(
32
  img, grid_size, tile_px, tile_sample,
33
  quantize_on, quantize_colors, show_grid
34
  ):
35
+ """Full end-to-end mosaic pipeline."""
36
 
37
  if img is None:
38
  return None, None, None, "Upload an image first."
 
40
  img_np = np.array(img.convert("RGB"))
41
  grid_n = int(grid_size)
42
 
43
+ # --- Crop image to perfect grid division ---
44
  base = crop_to_multiple(img_np, grid_n)
45
 
46
+ # --- Optional quantization ---
47
  if quantize_on:
48
  try:
49
  q = Image.fromarray(base).quantize(
 
55
  except Exception as e:
56
  return None, None, None, f"Quantization failed: {e}"
57
 
58
+ # --- Compute LAB means ---
59
  try:
60
  t0 = time.perf_counter()
61
  cell_means, dims = compute_cell_means_lab(base, grid_n)
 
65
 
66
  w, h, cell_w, cell_h = dims
67
 
68
+ # --- Prepare scaled tiles ---
69
  TM.prepare_scaled_tiles(cell_w, cell_h)
70
 
71
+ # --- FAISS lookup ---
72
  try:
73
  idxs = TM.lookup_tiles(cell_means)
74
  except Exception as e:
75
  return None, None, None, f"Tile lookup failed: {e}"
76
 
77
+ # --- Build mosaic ---
78
  builder = MosaicBuilder(TM)
79
  try:
80
  mosaic_np = builder.build(idxs, dims, grid_n)
 
83
 
84
  t2 = time.perf_counter()
85
 
86
+ # --- Metrics ---
87
  try:
88
  mse_val = mse(base, mosaic_np)
89
  ssim_val = ssim_rgb(base, mosaic_np)
90
+ except Exception:
91
  mse_val, ssim_val = -1, -1
92
 
93
+ # --- Optional grid overlay ---
94
  segmented = Image.fromarray(base)
95
  if show_grid:
96
  seg = segmented.copy()
 
101
  draw.line([(0, y), (w, y)], fill="red", width=1)
102
  segmented = seg
103
 
104
+ # --- Build report text ---
105
  report = (
106
  f"MSE: {mse_val:.2f}\n"
107
  f"SSIM: {ssim_val:.4f}\n\n"
 
118
  )
119
 
120
 
121
+ # ---------------------------------------------------------
122
  # GRADIO UI
123
+ # ---------------------------------------------------------
124
  def build_demo():
125
  with gr.Blocks(title="High-Performance Mosaic Generator") as demo:
126
 
127
  gr.Markdown("# ⚡ High-Performance Mosaic Generator (Lab 5)")
128
+ gr.Markdown("Ultra-fast FAISS-powered image mosaic generator.\n")
129
 
130
  with gr.Row():
131
 
132
+ # ---------------- LEFT COLUMN --------------------
 
 
133
  with gr.Column(scale=1):
134
 
135
  img_in = gr.Image(type="pil", label="Upload Image")
136
 
137
+ grid_size = gr.Radio(
138
+ ["16", "32", "64", "128"],
139
+ value="32",
140
+ label="Grid Size"
141
+ )
142
+ tile_px = gr.Radio(
143
+ ["8", "16", "24", "32"],
144
+ value="16",
145
+ label="Tile Resolution (px)"
146
+ )
147
 
148
  tile_sample = gr.Slider(
149
  512, 20000, step=256, value=2048,
 
160
 
161
  run_btn = gr.Button("Generate Mosaic", variant="primary")
162
 
163
+ # ---------------- Example Images (HF-safe URLs) ----------------
164
+ gr.Markdown("### Example Images (Click to Load)")
 
 
165
 
166
  example_urls = [
167
+ ["https://huggingface.co/datasets/hf-internal-testing/dog/resolve/main/dog.jpg"],
168
+ ["https://huggingface.co/datasets/mishig/sample_images/resolve/main/cat.png"],
169
+ ["https://huggingface.co/datasets/mishig/sample_images/resolve/main/mountain.png"],
170
  ]
171
 
172
  gr.Examples(
173
  examples=example_urls,
174
  inputs=[img_in],
175
+ label="",
176
  cache_examples=False
177
  )
178
 
179
+ # ---------------- RIGHT COLUMN --------------------
 
 
180
  with gr.Column(scale=2):
181
 
182
  with gr.Tab("Original"):
 
190
 
191
  report = gr.Textbox(label="Timing & Metrics", lines=10)
192
 
193
+ # Connect button → function
194
  run_btn.click(
195
  fn=run_pipeline,
196
  inputs=[img_in, grid_size, tile_px, tile_sample,
 
201
  return demo
202
 
203
 
204
+ # ---------------------------------------------------------
205
  # LAUNCH
206
+ # ---------------------------------------------------------
207
  if __name__ == "__main__":
208
  demo = build_demo()
209
  demo.launch()