Semnykcz commited on
Commit
3ede7ef
·
verified ·
1 Parent(s): 7fc1882

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. .github/workflows/update_space.yml +28 -0
  2. app.py +207 -52
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v2
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: '3.9'
20
+
21
+ - name: Install Gradio
22
+ run: python -m pip install gradio
23
+
24
+ - name: Log in to Hugging Face
25
+ run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
26
+
27
+ - name: Deploy to Spaces
28
+ run: gradio deploy
app.py CHANGED
@@ -18,28 +18,48 @@ class PhotoUpscaler:
18
  self.load_default_model()
19
 
20
  def load_default_model(self):
21
- """Load default upscaling model"""
22
- try:
23
- # Using a Real-ESRGAN style model from Hugging Face
24
- self.current_model = "caidas/swin2SR-realworld-sr-x4-64-bsrgan-psnr"
25
- self.upscaler = pipeline(
26
- "image-to-image",
27
- model=self.current_model,
28
- device=0 if self.device == "cuda" else -1
29
- )
30
- return f"✅ Model načten: {self.current_model}"
31
- except Exception as e:
32
- # Fallback to a simpler approach
33
- self.current_model = "microsoft/swin2SR-compressed-sr-x2-48"
34
  try:
35
- self.upscaler = pipeline(
36
- "image-to-image",
37
- model=self.current_model,
38
- device=0 if self.device == "cuda" else -1
39
- )
40
- return f"✅ Fallback model načten: {self.current_model}"
41
- except:
42
- return f"❌ Chyba při načítání modelů: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  def upscale_image(self, image, scale_factor=2, model_choice="default"):
45
  """Upscale image using selected model"""
@@ -62,18 +82,50 @@ class PhotoUpscaler:
62
  if model_choice != "default" and model_choice != self.current_model:
63
  self.load_model(model_choice)
64
 
65
- # Perform upscaling
66
  if self.upscaler:
67
- # For pipeline-based upscaling
68
- upscaled = self.upscaler(image)
69
- if isinstance(upscaled, list):
70
- upscaled = upscaled[0]
71
- if hasattr(upscaled, 'images'):
72
- upscaled = upscaled.images[0]
73
- elif isinstance(upscaled, dict) and 'image' in upscaled:
74
- upscaled = upscaled['image']
75
-
76
- return upscaled, f"✅ Obrázek zvětšen pomocí {self.current_model}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  else:
78
  # Simple fallback upscaling
79
  new_size = tuple(int(dim * scale_factor) for dim in image.size)
@@ -84,17 +136,57 @@ class PhotoUpscaler:
84
  return None, f"❌ Chyba při zpracování: {str(e)}"
85
 
86
  def load_model(self, model_name):
87
- """Load specific model"""
88
  try:
89
  self.current_model = model_name
90
- self.upscaler = pipeline(
91
- "image-to-image",
92
- model=model_name,
93
- device=0 if self.device == "cuda" else -1
94
- )
95
- return f"✅ Model změněn na: {model_name}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  except Exception as e:
97
- return f"❌ Chyba při načítání modelu {model_name}: {str(e)}"
98
 
99
  # Initialize upscaler
100
  upscaler = PhotoUpscaler()
@@ -102,13 +194,50 @@ upscaler = PhotoUpscaler()
102
  # Available models for upscaling
103
  UPSCALING_MODELS = [
104
  "default",
105
- "microsoft/swin2SR-compressed-sr-x2-48",
106
- "microsoft/swin2SR-compressed-sr-x4-48",
 
 
 
 
107
  "caidas/swin2SR-realworld-sr-x4-64-bsrgan-psnr",
 
 
 
 
 
 
 
 
 
108
  "microsoft/swin2SR-classical-sr-x2-64",
109
- "microsoft/swin2SR-classical-sr-x4-64"
 
 
 
 
 
 
110
  ]
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  def process_upscaling(image, scale_factor, model_choice, hf_token):
113
  """Main processing function"""
114
  # Login to HuggingFace if token provided
@@ -175,10 +304,10 @@ with gr.Blocks(
175
  )
176
 
177
  model_choice = gr.Dropdown(
178
- choices=UPSCALING_MODELS,
179
  value="default",
180
  label="Vyberte model",
181
- info="Různé modely pro různé typy obrázků"
182
  )
183
 
184
  hf_token = gr.Textbox(
@@ -221,14 +350,40 @@ with gr.Blocks(
221
  outputs=status_text
222
  )
223
 
224
- # Examples
225
- gr.Markdown("### 📋 Tipy pro použití")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  gr.Markdown("""
227
- - **Nejlepší výsledky**: Používejte obrázky s rozlišením 256x256 až 512x512 pixelů
228
- - **Modely**: Různé modely jsou optimalizované pro různé typy obrázků
229
- - **Real-world modely**: Nejlepší pro fotografie z reálného světa
230
- - **Classical modely**: Vhodné pro umělé nebo digitální obrázky
231
- - **HF Token**: Zadejte pro přístup k nejnovějším modelům
 
 
 
 
 
 
 
232
  """)
233
 
234
  if __name__ == "__main__":
 
18
  self.load_default_model()
19
 
20
  def load_default_model(self):
21
+ """Load default upscaling model with Real-ESRGAN priority"""
22
+ # Priority list of models to try
23
+ priority_models = [
24
+ "ai-forever/Real-ESRGAN",
25
+ "sberbank-ai/Real-ESRGAN",
26
+ "caidas/swin2SR-realworld-sr-x4-64-bsrgan-psnr",
27
+ "microsoft/swin2SR-compressed-sr-x2-48"
28
+ ]
29
+
30
+ for model_name in priority_models:
 
 
 
31
  try:
32
+ self.current_model = model_name
33
+ if "Real-ESRGAN" in model_name:
34
+ # Special handling for Real-ESRGAN models
35
+ try:
36
+ from diffusers import StableDiffusionUpscalePipeline
37
+ self.upscaler = StableDiffusionUpscalePipeline.from_pretrained(
38
+ model_name,
39
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
40
+ ).to(self.device)
41
+ return f"✅ Real-ESRGAN model načten: {self.current_model}"
42
+ except:
43
+ # Fallback to regular pipeline
44
+ self.upscaler = pipeline(
45
+ "image-to-image",
46
+ model=model_name,
47
+ device=0 if self.device == "cuda" else -1
48
+ )
49
+ return f"✅ Model načten: {self.current_model}"
50
+ else:
51
+ # Regular Swin2SR models
52
+ self.upscaler = pipeline(
53
+ "image-to-image",
54
+ model=model_name,
55
+ device=0 if self.device == "cuda" else -1
56
+ )
57
+ return f"✅ Model načten: {self.current_model}"
58
+ except Exception as e:
59
+ print(f"Nepodařilo se načíst {model_name}: {e}")
60
+ continue
61
+
62
+ return f"❌ Nepodařilo se načíst žádný model"
63
 
64
  def upscale_image(self, image, scale_factor=2, model_choice="default"):
65
  """Upscale image using selected model"""
 
82
  if model_choice != "default" and model_choice != self.current_model:
83
  self.load_model(model_choice)
84
 
85
+ # Perform upscaling based on model type
86
  if self.upscaler:
87
+ try:
88
+ if "Real-ESRGAN" in self.current_model:
89
+ # Special handling for Real-ESRGAN models
90
+ if hasattr(self.upscaler, '__call__'):
91
+ # Diffusers pipeline
92
+ prompt = "high quality, detailed, sharp"
93
+ upscaled = self.upscaler(
94
+ prompt=prompt,
95
+ image=image,
96
+ num_inference_steps=20,
97
+ guidance_scale=0
98
+ ).images[0]
99
+ else:
100
+ # Regular pipeline fallback
101
+ upscaled = self.upscaler(image)
102
+ elif "stable-diffusion" in self.current_model.lower():
103
+ # Stable Diffusion upscaler
104
+ from diffusers import StableDiffusionUpscalePipeline
105
+ prompt = "high quality, detailed, sharp, realistic"
106
+ upscaled = self.upscaler(
107
+ prompt=prompt,
108
+ image=image,
109
+ num_inference_steps=20
110
+ ).images[0]
111
+ else:
112
+ # Standard Swin2SR and other models
113
+ upscaled = self.upscaler(image)
114
+ if isinstance(upscaled, list):
115
+ upscaled = upscaled[0]
116
+ if hasattr(upscaled, 'images'):
117
+ upscaled = upscaled.images[0]
118
+ elif isinstance(upscaled, dict) and 'image' in upscaled:
119
+ upscaled = upscaled['image']
120
+
121
+ return upscaled, f"✅ Obrázek zvětšen pomocí {MODEL_DESCRIPTIONS.get(self.current_model, self.current_model)}"
122
+
123
+ except Exception as model_error:
124
+ print(f"Model error: {model_error}")
125
+ # Fallback to simple upscaling
126
+ new_size = tuple(int(dim * scale_factor) for dim in image.size)
127
+ upscaled = image.resize(new_size, Image.Resampling.LANCZOS)
128
+ return upscaled, f"✅ Obrázek zvětšen pomocí klasického algoritmu (model selhání)"
129
  else:
130
  # Simple fallback upscaling
131
  new_size = tuple(int(dim * scale_factor) for dim in image.size)
 
136
  return None, f"❌ Chyba při zpracování: {str(e)}"
137
 
138
  def load_model(self, model_name):
139
+ """Load specific model with enhanced support for different model types"""
140
  try:
141
  self.current_model = model_name
142
+
143
+ if "Real-ESRGAN" in model_name:
144
+ # Try Real-ESRGAN specific loading
145
+ try:
146
+ from diffusers import StableDiffusionUpscalePipeline
147
+ self.upscaler = StableDiffusionUpscalePipeline.from_pretrained(
148
+ model_name,
149
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
150
+ ).to(self.device)
151
+ return f"✅ Real-ESRGAN model načten: {MODEL_DESCRIPTIONS.get(model_name, model_name)}"
152
+ except:
153
+ # Fallback to regular pipeline
154
+ self.upscaler = pipeline(
155
+ "image-to-image",
156
+ model=model_name,
157
+ device=0 if self.device == "cuda" else -1
158
+ )
159
+ return f"✅ Model načten (fallback): {MODEL_DESCRIPTIONS.get(model_name, model_name)}"
160
+
161
+ elif "stable-diffusion" in model_name.lower():
162
+ # Stable Diffusion upscaler
163
+ from diffusers import StableDiffusionUpscalePipeline
164
+ self.upscaler = StableDiffusionUpscalePipeline.from_pretrained(
165
+ model_name,
166
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
167
+ ).to(self.device)
168
+ return f"✅ SD Upscaler načten: {MODEL_DESCRIPTIONS.get(model_name, model_name)}"
169
+
170
+ elif "ldm" in model_name.lower():
171
+ # LDM models
172
+ from diffusers import LDMSuperResolutionPipeline
173
+ self.upscaler = LDMSuperResolutionPipeline.from_pretrained(
174
+ model_name,
175
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
176
+ ).to(self.device)
177
+ return f"✅ LDM model načten: {MODEL_DESCRIPTIONS.get(model_name, model_name)}"
178
+
179
+ else:
180
+ # Standard pipeline for Swin2SR and similar models
181
+ self.upscaler = pipeline(
182
+ "image-to-image",
183
+ model=model_name,
184
+ device=0 if self.device == "cuda" else -1
185
+ )
186
+ return f"✅ Model načten: {MODEL_DESCRIPTIONS.get(model_name, model_name)}"
187
+
188
  except Exception as e:
189
+ return f"❌ Chyba při načítání modelu {MODEL_DESCRIPTIONS.get(model_name, model_name)}: {str(e)}"
190
 
191
  # Initialize upscaler
192
  upscaler = PhotoUpscaler()
 
194
  # Available models for upscaling
195
  UPSCALING_MODELS = [
196
  "default",
197
+ # Real-ESRGAN models (nejlepší pro realistické fotografie)
198
+ "ai-forever/Real-ESRGAN",
199
+ "sberbank-ai/Real-ESRGAN",
200
+ "philz1337x/clarity-upscaler",
201
+
202
+ # BSRGAN models (vynikající pro reálné obrázky)
203
  "caidas/swin2SR-realworld-sr-x4-64-bsrgan-psnr",
204
+ "caidas/swin2SR-realworld-sr-x2-64-bsrgan-psnr",
205
+
206
+ # SwinIR models (state-of-the-art)
207
+ "caidas/swinIR-M-real-sr-x4-64-bsrgan-psnr",
208
+ "caidas/swinIR-L-real-sr-x4-64-bsrgan-psnr",
209
+
210
+ # Microsoft Swin2SR (optimalizované)
211
+ "microsoft/swin2SR-compressed-sr-x2-48",
212
+ "microsoft/swin2SR-compressed-sr-x4-48",
213
  "microsoft/swin2SR-classical-sr-x2-64",
214
+ "microsoft/swin2SR-classical-sr-x4-64",
215
+ "microsoft/swin2SR-realworld-sr-x4-64-bsrgan-psnr",
216
+
217
+ # Další pokročilé modely
218
+ "Kolors/Kolors-IP-Adapter-FaceID-Plus",
219
+ "stabilityai/stable-diffusion-x4-upscaler",
220
+ "CompVis/ldm-super-resolution-4x-openimages"
221
  ]
222
 
223
+ # Model descriptions for better user experience
224
+ MODEL_DESCRIPTIONS = {
225
+ "default": "🎯 Výchozí model - rychlý a spolehlivý",
226
+ "ai-forever/Real-ESRGAN": "🏆 Real-ESRGAN - nejlepší pro fotografie",
227
+ "sberbank-ai/Real-ESRGAN": "⭐ Real-ESRGAN Sberbank - vylepšená verze",
228
+ "philz1337x/clarity-upscaler": "✨ Clarity Upscaler - ultra ostrý",
229
+ "caidas/swin2SR-realworld-sr-x4-64-bsrgan-psnr": "🌟 BSRGAN 4x - premium kvalita",
230
+ "caidas/swin2SR-realworld-sr-x2-64-bsrgan-psnr": "🌟 BSRGAN 2x - rychlejší",
231
+ "caidas/swinIR-M-real-sr-x4-64-bsrgan-psnr": "🚀 SwinIR Medium - vyváženost",
232
+ "caidas/swinIR-L-real-sr-x4-64-bsrgan-psnr": "🔥 SwinIR Large - maximální kvalita",
233
+ "microsoft/swin2SR-compressed-sr-x2-48": "⚡ Komprimovaný 2x - rychlý",
234
+ "microsoft/swin2SR-compressed-sr-x4-48": "⚡ Komprimovaný 4x - rychlý",
235
+ "microsoft/swin2SR-classical-sr-x2-64": "🎨 Klasický 2x - digitální obrázky",
236
+ "microsoft/swin2SR-classical-sr-x4-64": "🎨 Klasický 4x - digitální obrázky",
237
+ "stabilityai/stable-diffusion-x4-upscaler": "🎭 SD Upscaler - kreativní vylepšení",
238
+ "CompVis/ldm-super-resolution-4x-openimages": "🧠 LDM - generativní upscaling"
239
+ }
240
+
241
  def process_upscaling(image, scale_factor, model_choice, hf_token):
242
  """Main processing function"""
243
  # Login to HuggingFace if token provided
 
304
  )
305
 
306
  model_choice = gr.Dropdown(
307
+ choices=[(MODEL_DESCRIPTIONS.get(model, model), model) for model in UPSCALING_MODELS],
308
  value="default",
309
  label="Vyberte model",
310
+ info="Různé modely pro různé typy obrázků - Real-ESRGAN nejlepší pro fotografie"
311
  )
312
 
313
  hf_token = gr.Textbox(
 
350
  outputs=status_text
351
  )
352
 
353
+ # Examples and tips
354
+ gr.Markdown("### 📋 Tipy pro nejlepší výsledky")
355
+
356
+ with gr.Row():
357
+ with gr.Column():
358
+ gr.Markdown("""
359
+ **🏆 Nejlepší modely pro fotografie:**
360
+ - **Real-ESRGAN**: Nejkvalitnější pro reálné fotky
361
+ - **BSRGAN**: Vynikající detail a ostrost
362
+ - **SwinIR Large**: Maximální kvalita, pomalejší
363
+ - **Clarity Upscaler**: Ultra ostrý výsledek
364
+ """)
365
+
366
+ with gr.Column():
367
+ gr.Markdown("""
368
+ **⚡ Rychlé modely:**
369
+ - **Komprimované modely**: Rychlé zpracování
370
+ - **2x modely**: Rychlejší než 4x verze
371
+ - **Classical modely**: Pro digitální obrázky
372
+ """)
373
+
374
  gr.Markdown("""
375
+ ### 💡 Doporučení podle typu obrázku:
376
+ - **Portréty**: Real-ESRGAN nebo SwinIR Large
377
+ - **Krajiny**: BSRGAN nebo Clarity Upscaler
378
+ - **Staré fotky**: Real-ESRGAN s noise reduction
379
+ - **Digitální art**: Classical nebo Stable Diffusion Upscaler
380
+ - **Dokumenty**: SwinIR Medium pro čitelnost
381
+
382
+ ### ⚙️ Optimalizace výkonu:
383
+ - **GPU**: Automaticky detekováno pro rychlejší zpracování
384
+ - **Velikost**: 256-512px pro nejlepší poměr rychlost/kvalita
385
+ - **Formát**: PNG zachovává nejvyšší kvalitu
386
+ - **HF Token**: Pro přístup k nejnovějším modelům
387
  """)
388
 
389
  if __name__ == "__main__":