Aguilar Elizondo commited on
Commit
20f5f44
Β·
1 Parent(s): afabb78

Simplify to gr.Interface for HF Spaces compatibility

Browse files
Files changed (2) hide show
  1. app.py +44 -163
  2. app_blocks.py.bak +222 -0
app.py CHANGED
@@ -1,7 +1,5 @@
1
  """
2
- Architecture AI Enhancer - Gradio App for Hugging Face Spaces
3
-
4
- This file creates a Gradio interface for the enhancement pipeline.
5
  """
6
  import gradio as gr
7
  import torch
@@ -9,7 +7,6 @@ from PIL import Image
9
  import logging
10
  from pathlib import Path
11
  import sys
12
- import os
13
 
14
  # Add backend to path
15
  sys.path.insert(0, str(Path(__file__).parent))
@@ -17,206 +14,90 @@ sys.path.insert(0, str(Path(__file__).parent))
17
  from backend.services.diffusion_pipeline import get_pipeline_manager, enhance_image as enhance_with_diffusion
18
  from backend.services.upscaler import upscale_image
19
  from backend.services.postprocess import postprocess_image
20
- from backend.config import settings
21
 
22
  # Configure logging
23
  logging.basicConfig(level=logging.INFO)
24
  logger = logging.getLogger(__name__)
25
 
26
- # Initialize pipeline manager (lazy loading)
27
  pipeline_manager = None
28
 
29
  def initialize_models():
30
- """Initialize all models on first use"""
31
  global pipeline_manager
32
-
33
  if pipeline_manager is None:
34
  logger.info("Loading Stable Diffusion pipeline...")
35
  pipeline_manager = get_pipeline_manager()
36
 
37
- def enhance_image_gradio(
38
  input_image: Image.Image,
39
- strength: float = 0.3,
40
- guidance_scale: float = 5.5,
41
- custom_prompt: str = "",
42
- use_upscaler: bool = True,
43
- use_postprocess: bool = True
44
  ) -> Image.Image:
45
- """
46
- Enhance architectural image using AI pipeline
47
-
48
- Args:
49
- input_image: Input PIL Image
50
- strength: Denoising strength (0.1-0.8)
51
- guidance_scale: CFG scale (1.0-15.0)
52
- custom_prompt: Optional custom prompt
53
- use_upscaler: Apply upscaling
54
- use_postprocess: Apply post-processing
55
-
56
- Returns:
57
- Enhanced PIL Image
58
- """
59
  try:
 
 
60
  # Initialize models
61
- logger.info("Loading models...")
62
  initialize_models()
63
 
64
  # Step 1: AI Enhancement
65
- logger.info("Preprocessing image...")
66
-
67
- prompt = custom_prompt if custom_prompt else settings.DEFAULT_PROMPT
68
-
69
- logger.info("Enhancing with AI (this may take a few minutes)...")
70
-
71
- enhanced = pipeline_manager.run_inference(
72
- image=input_image,
73
- prompt=prompt,
74
- negative_prompt=settings.NEGATIVE_PROMPT,
75
  strength=strength,
76
  guidance_scale=guidance_scale,
77
  num_inference_steps=30
78
  )
79
 
80
- logger.info("AI enhancement complete!")
81
-
82
- # Step 2: Optional Upscaling
83
  if use_upscaler:
84
  logger.info("Upscaling image...")
85
  enhanced = upscale_image(enhanced, scale=2)
86
- logger.info("Upscaling complete!")
87
 
88
- # Step 3: Optional Post-processing
89
  if use_postprocess:
90
- logger.info("Applying final touches...")
91
  enhanced = postprocess_image(
92
  enhanced,
93
  clahe=True,
94
  sharpen=1.0,
95
  color_enhance=1.1
96
  )
97
- logger.info("Post-processing complete!")
98
 
99
- logger.info("Enhancement process complete!")
100
  return enhanced
101
 
102
  except Exception as e:
103
  logger.error(f"Enhancement failed: {e}", exc_info=True)
104
- raise gr.Error(f"Enhancement failed: {str(e)}")
105
 
106
- # Create Gradio interface
107
- with gr.Blocks(title="Architecture AI Enhancer", theme=gr.themes.Soft()) as demo:
108
- gr.Markdown("""
109
- # πŸ—οΈ Architecture AI Enhancer
110
-
111
- Transform your architectural renders with AI-powered enhancement using Stable Diffusion 1.5.
112
-
113
- **Upload an image** and adjust the settings below to enhance your architectural visualization.
114
- """)
115
-
116
- with gr.Row():
117
- with gr.Column():
118
- input_image = gr.Image(
119
- label="πŸ“€ Input Image",
120
- type="pil",
121
- height=400
122
- )
123
-
124
- with gr.Accordion("βš™οΈ Advanced Settings", open=False):
125
- strength = gr.Slider(
126
- minimum=0.1,
127
- maximum=0.8,
128
- value=0.3,
129
- step=0.05,
130
- label="Denoising Strength",
131
- info="Lower = more faithful to input, Higher = more creative"
132
- )
133
-
134
- guidance_scale = gr.Slider(
135
- minimum=1.0,
136
- maximum=15.0,
137
- value=5.5,
138
- step=0.5,
139
- label="Guidance Scale",
140
- info="How closely to follow the prompt"
141
- )
142
-
143
- custom_prompt = gr.Textbox(
144
- label="Custom Prompt (optional)",
145
- placeholder="professional architectural photography, detailed, high quality...",
146
- lines=3
147
- )
148
-
149
- use_upscaler = gr.Checkbox(
150
- label="Enable Upscaling (2x)",
151
- value=True
152
- )
153
-
154
- use_postprocess = gr.Checkbox(
155
- label="Enable Post-Processing",
156
- value=True,
157
- info="Adds photographic enhancements"
158
- )
159
-
160
- enhance_btn = gr.Button("✨ Enhance Image", variant="primary", size="lg")
161
-
162
- with gr.Column():
163
- output_image = gr.Image(
164
- label="βœ… Enhanced Result",
165
- type="pil",
166
- height=400
167
- )
168
-
169
- gr.Markdown("""
170
- ### πŸ“ Tips for Best Results:
171
- - Use high-quality architectural renders as input
172
- - Start with default settings and adjust if needed
173
- - Lower strength for subtle enhancements
174
- - Higher strength for more dramatic changes
175
- - Processing takes 2-5 minutes on CPU, ~30 seconds on GPU
176
- """)
177
-
178
- gr.Markdown("""
179
- ---
180
- ### πŸ”§ Technical Details:
181
- - **Model**: Stable Diffusion 1.5
182
- - **Upscaler**: ESRGAN (optional)
183
- - **Processing**: CPU/GPU automatic detection
184
- - **Version**: 1.0.0
185
-
186
- ### πŸ“š Resources:
187
- - [GitHub Repository](#)
188
- - [Documentation](#)
189
- - [Report Issues](#)
190
- """)
191
-
192
- # Connect the enhance button
193
- enhance_btn.click(
194
- fn=enhance_image_gradio,
195
- inputs=[
196
- input_image,
197
- strength,
198
- guidance_scale,
199
- custom_prompt,
200
- use_upscaler,
201
- use_postprocess
202
- ],
203
- outputs=output_image
204
- )
205
 
206
- # Launch configuration
207
  if __name__ == "__main__":
208
- demo.queue(max_size=10) # Enable queue for multiple users
209
-
210
- # Detect if running on HF Spaces
211
- is_hf_space = os.getenv("SPACE_ID") is not None
212
-
213
- if is_hf_space:
214
- # HF Spaces configuration
215
- demo.launch(
216
- server_name="0.0.0.0",
217
- server_port=7860,
218
- show_api=False
219
- )
220
- else:
221
- # Local development
222
- demo.launch(share=True)
 
1
  """
2
+ Architecture AI Enhancer - Simple Gradio Interface for HF Spaces
 
 
3
  """
4
  import gradio as gr
5
  import torch
 
7
  import logging
8
  from pathlib import Path
9
  import sys
 
10
 
11
  # Add backend to path
12
  sys.path.insert(0, str(Path(__file__).parent))
 
14
  from backend.services.diffusion_pipeline import get_pipeline_manager, enhance_image as enhance_with_diffusion
15
  from backend.services.upscaler import upscale_image
16
  from backend.services.postprocess import postprocess_image
 
17
 
18
  # Configure logging
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
21
 
22
+ # Initialize pipeline manager
23
  pipeline_manager = None
24
 
25
  def initialize_models():
26
+ """Initialize models on first use"""
27
  global pipeline_manager
 
28
  if pipeline_manager is None:
29
  logger.info("Loading Stable Diffusion pipeline...")
30
  pipeline_manager = get_pipeline_manager()
31
 
32
+ def enhance_image_simple(
33
  input_image: Image.Image,
34
+ strength: float,
35
+ guidance_scale: float,
36
+ use_upscaler: bool,
37
+ use_postprocess: bool
 
38
  ) -> Image.Image:
39
+ """Enhance architectural image"""
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  try:
41
+ logger.info("Starting enhancement process...")
42
+
43
  # Initialize models
 
44
  initialize_models()
45
 
46
  # Step 1: AI Enhancement
47
+ logger.info("Applying AI enhancement...")
48
+ enhanced = enhance_with_diffusion(
49
+ pipeline_manager,
50
+ input_image,
51
+ prompt="professional architectural photography, highly detailed, 8k, photorealistic",
 
 
 
 
 
52
  strength=strength,
53
  guidance_scale=guidance_scale,
54
  num_inference_steps=30
55
  )
56
 
57
+ # Step 2: Upscaling
 
 
58
  if use_upscaler:
59
  logger.info("Upscaling image...")
60
  enhanced = upscale_image(enhanced, scale=2)
 
61
 
62
+ # Step 3: Post-processing
63
  if use_postprocess:
64
+ logger.info("Post-processing...")
65
  enhanced = postprocess_image(
66
  enhanced,
67
  clahe=True,
68
  sharpen=1.0,
69
  color_enhance=1.1
70
  )
 
71
 
72
+ logger.info("Enhancement complete!")
73
  return enhanced
74
 
75
  except Exception as e:
76
  logger.error(f"Enhancement failed: {e}", exc_info=True)
77
+ raise
78
 
79
+ # Create simple interface
80
+ iface = gr.Interface(
81
+ fn=enhance_image_simple,
82
+ inputs=[
83
+ gr.Image(label="Input Image", type="pil"),
84
+ gr.Slider(0.1, 0.8, value=0.3, step=0.05, label="Strength"),
85
+ gr.Slider(1.0, 15.0, value=5.5, step=0.5, label="Guidance Scale"),
86
+ gr.Checkbox(label="Enable Upscaling", value=True),
87
+ gr.Checkbox(label="Enable Post-Processing", value=True)
88
+ ],
89
+ outputs=gr.Image(label="Enhanced Image", type="pil"),
90
+ title="πŸ›οΈ Architecture AI Enhancer",
91
+ description="Transform architectural renders with AI-powered enhancement using Stable Diffusion 1.5",
92
+ article="""
93
+ ### Tips for Best Results:
94
+ - Use high-quality architectural renders
95
+ - Lower strength = more faithful to input
96
+ - Higher strength = more creative output
97
+ - Processing takes 2-5 minutes on CPU
98
+ """,
99
+ examples=None
100
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
 
102
  if __name__ == "__main__":
103
+ iface.queue().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_blocks.py.bak ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Architecture AI Enhancer - Gradio App for Hugging Face Spaces
3
+
4
+ This file creates a Gradio interface for the enhancement pipeline.
5
+ """
6
+ import gradio as gr
7
+ import torch
8
+ from PIL import Image
9
+ import logging
10
+ from pathlib import Path
11
+ import sys
12
+ import os
13
+
14
+ # Add backend to path
15
+ sys.path.insert(0, str(Path(__file__).parent))
16
+
17
+ from backend.services.diffusion_pipeline import get_pipeline_manager, enhance_image as enhance_with_diffusion
18
+ from backend.services.upscaler import upscale_image
19
+ from backend.services.postprocess import postprocess_image
20
+ from backend.config import settings
21
+
22
+ # Configure logging
23
+ logging.basicConfig(level=logging.INFO)
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # Initialize pipeline manager (lazy loading)
27
+ pipeline_manager = None
28
+
29
+ def initialize_models():
30
+ """Initialize all models on first use"""
31
+ global pipeline_manager
32
+
33
+ if pipeline_manager is None:
34
+ logger.info("Loading Stable Diffusion pipeline...")
35
+ pipeline_manager = get_pipeline_manager()
36
+
37
+ def enhance_image_gradio(
38
+ input_image: Image.Image,
39
+ strength: float = 0.3,
40
+ guidance_scale: float = 5.5,
41
+ custom_prompt: str = "",
42
+ use_upscaler: bool = True,
43
+ use_postprocess: bool = True
44
+ ) -> Image.Image:
45
+ """
46
+ Enhance architectural image using AI pipeline
47
+
48
+ Args:
49
+ input_image: Input PIL Image
50
+ strength: Denoising strength (0.1-0.8)
51
+ guidance_scale: CFG scale (1.0-15.0)
52
+ custom_prompt: Optional custom prompt
53
+ use_upscaler: Apply upscaling
54
+ use_postprocess: Apply post-processing
55
+
56
+ Returns:
57
+ Enhanced PIL Image
58
+ """
59
+ try:
60
+ # Initialize models
61
+ logger.info("Loading models...")
62
+ initialize_models()
63
+
64
+ # Step 1: AI Enhancement
65
+ logger.info("Preprocessing image...")
66
+
67
+ prompt = custom_prompt if custom_prompt else settings.DEFAULT_PROMPT
68
+
69
+ logger.info("Enhancing with AI (this may take a few minutes)...")
70
+
71
+ enhanced = pipeline_manager.run_inference(
72
+ image=input_image,
73
+ prompt=prompt,
74
+ negative_prompt=settings.NEGATIVE_PROMPT,
75
+ strength=strength,
76
+ guidance_scale=guidance_scale,
77
+ num_inference_steps=30
78
+ )
79
+
80
+ logger.info("AI enhancement complete!")
81
+
82
+ # Step 2: Optional Upscaling
83
+ if use_upscaler:
84
+ logger.info("Upscaling image...")
85
+ enhanced = upscale_image(enhanced, scale=2)
86
+ logger.info("Upscaling complete!")
87
+
88
+ # Step 3: Optional Post-processing
89
+ if use_postprocess:
90
+ logger.info("Applying final touches...")
91
+ enhanced = postprocess_image(
92
+ enhanced,
93
+ clahe=True,
94
+ sharpen=1.0,
95
+ color_enhance=1.1
96
+ )
97
+ logger.info("Post-processing complete!")
98
+
99
+ logger.info("Enhancement process complete!")
100
+ return enhanced
101
+
102
+ except Exception as e:
103
+ logger.error(f"Enhancement failed: {e}", exc_info=True)
104
+ raise gr.Error(f"Enhancement failed: {str(e)}")
105
+
106
+ # Create Gradio interface
107
+ with gr.Blocks(title="Architecture AI Enhancer", theme=gr.themes.Soft()) as demo:
108
+ gr.Markdown("""
109
+ # πŸ—οΈ Architecture AI Enhancer
110
+
111
+ Transform your architectural renders with AI-powered enhancement using Stable Diffusion 1.5.
112
+
113
+ **Upload an image** and adjust the settings below to enhance your architectural visualization.
114
+ """)
115
+
116
+ with gr.Row():
117
+ with gr.Column():
118
+ input_image = gr.Image(
119
+ label="πŸ“€ Input Image",
120
+ type="pil",
121
+ height=400
122
+ )
123
+
124
+ with gr.Accordion("βš™οΈ Advanced Settings", open=False):
125
+ strength = gr.Slider(
126
+ minimum=0.1,
127
+ maximum=0.8,
128
+ value=0.3,
129
+ step=0.05,
130
+ label="Denoising Strength",
131
+ info="Lower = more faithful to input, Higher = more creative"
132
+ )
133
+
134
+ guidance_scale = gr.Slider(
135
+ minimum=1.0,
136
+ maximum=15.0,
137
+ value=5.5,
138
+ step=0.5,
139
+ label="Guidance Scale",
140
+ info="How closely to follow the prompt"
141
+ )
142
+
143
+ custom_prompt = gr.Textbox(
144
+ label="Custom Prompt (optional)",
145
+ placeholder="professional architectural photography, detailed, high quality...",
146
+ lines=3
147
+ )
148
+
149
+ use_upscaler = gr.Checkbox(
150
+ label="Enable Upscaling (2x)",
151
+ value=True
152
+ )
153
+
154
+ use_postprocess = gr.Checkbox(
155
+ label="Enable Post-Processing",
156
+ value=True,
157
+ info="Adds photographic enhancements"
158
+ )
159
+
160
+ enhance_btn = gr.Button("✨ Enhance Image", variant="primary", size="lg")
161
+
162
+ with gr.Column():
163
+ output_image = gr.Image(
164
+ label="βœ… Enhanced Result",
165
+ type="pil",
166
+ height=400
167
+ )
168
+
169
+ gr.Markdown("""
170
+ ### πŸ“ Tips for Best Results:
171
+ - Use high-quality architectural renders as input
172
+ - Start with default settings and adjust if needed
173
+ - Lower strength for subtle enhancements
174
+ - Higher strength for more dramatic changes
175
+ - Processing takes 2-5 minutes on CPU, ~30 seconds on GPU
176
+ """)
177
+
178
+ gr.Markdown("""
179
+ ---
180
+ ### πŸ”§ Technical Details:
181
+ - **Model**: Stable Diffusion 1.5
182
+ - **Upscaler**: ESRGAN (optional)
183
+ - **Processing**: CPU/GPU automatic detection
184
+ - **Version**: 1.0.0
185
+
186
+ ### πŸ“š Resources:
187
+ - [GitHub Repository](#)
188
+ - [Documentation](#)
189
+ - [Report Issues](#)
190
+ """)
191
+
192
+ # Connect the enhance button
193
+ enhance_btn.click(
194
+ fn=enhance_image_gradio,
195
+ inputs=[
196
+ input_image,
197
+ strength,
198
+ guidance_scale,
199
+ custom_prompt,
200
+ use_upscaler,
201
+ use_postprocess
202
+ ],
203
+ outputs=output_image
204
+ )
205
+
206
+ # Launch configuration
207
+ if __name__ == "__main__":
208
+ demo.queue(max_size=10) # Enable queue for multiple users
209
+
210
+ # Detect if running on HF Spaces
211
+ is_hf_space = os.getenv("SPACE_ID") is not None
212
+
213
+ if is_hf_space:
214
+ # HF Spaces configuration
215
+ demo.launch(
216
+ server_name="0.0.0.0",
217
+ server_port=7860,
218
+ show_api=False
219
+ )
220
+ else:
221
+ # Local development
222
+ demo.launch(share=True)