dannyroxas commited on
Commit
70a6f75
Β·
verified Β·
1 Parent(s): 0f7328e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -52
app.py CHANGED
@@ -20,58 +20,149 @@ class MultiAttributeClassifier:
20
  def load_classification_models(self):
21
  """Load all classification models and encoders"""
22
  print("Loading classification models...")
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  for category in self.categories:
25
  try:
26
  # Load model from correct path
27
  model_path = f"models/classification/{category}_model.h5"
28
  if os.path.exists(model_path):
 
29
  self.models[category] = tf.keras.models.load_model(model_path)
30
- print(f"βœ… Loaded {category} model")
31
 
32
  # Load encoder
33
  encoder_path = f"models/classification/{category}_encoder.pkl"
34
  if os.path.exists(encoder_path):
35
  with open(encoder_path, 'rb') as f:
36
  self.encoders[category] = pickle.load(f)
 
37
  else:
38
- print(f"⚠️ {category} encoder not found")
39
  else:
40
- print(f"⚠️ {category} model not found at {model_path}")
41
  except Exception as e:
42
  print(f"❌ Failed to load {category}: {e}")
 
 
 
 
43
 
44
  def load_gan_models(self):
45
  """Load all GAN models for style transfer"""
46
  print("Loading GAN models...")
47
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  gan_paths = {
49
- # Day/Night models
50
- 'day_to_night': 'models/gan/day_night/day_to_night_generator_final.keras',
51
- 'night_to_day': 'models/gan/day_night/night_to_day_generator_final.keras',
 
 
 
 
 
 
 
 
 
 
52
 
53
- # Foggy/Clear models
54
- 'foggy_to_clear': 'models/gan/foggy/foggy_to_normal_generator_final.keras',
55
- 'clear_to_foggy': 'models/gan/foggy/normal_to_foggy_generator_final.keras',
 
 
 
 
 
 
 
 
56
 
57
  # Japanese art models
58
- 'photo_to_japanese': 'models/gan/japanese/photo_to_ukiyoe_generator.keras',
59
- 'japanese_to_photo': 'models/gan/japanese/ukiyoe_to_photo_generator.keras',
 
 
 
 
 
 
 
 
60
 
61
  # Season models
62
- 'summer_to_winter': 'models/gan/summer_winter/summer_to_winter_generator_final.keras',
63
- 'winter_to_summer': 'models/gan/summer_winter/winter_to_summer_generator_final.keras'
 
 
 
 
 
 
 
 
64
  }
65
 
66
- for model_name, model_path in gan_paths.items():
67
- try:
68
- if os.path.exists(model_path):
69
- self.gan_models[model_name] = tf.keras.models.load_model(model_path)
70
- print(f"βœ… Loaded GAN: {model_name}")
71
- else:
72
- print(f"⚠️ GAN model not found: {model_path}")
73
- except Exception as e:
74
- print(f"❌ Failed to load GAN {model_name}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  def preprocess_image_for_classification(self, image_path):
77
  """Preprocess image for classification (224x224)"""
@@ -220,7 +311,6 @@ def get_available_transfers(classification_results):
220
  })
221
 
222
  # Add season transfers (these work regardless of season classification)
223
- # You might want to add season classification logic here if you have a season model
224
  transfers.extend([
225
  {
226
  'name': 'Add Winter Atmosphere',
@@ -239,7 +329,16 @@ def get_available_transfers(classification_results):
239
  return transfers
240
 
241
  # Initialize classifier globally
 
242
  classifier = MultiAttributeClassifier()
 
 
 
 
 
 
 
 
243
 
244
  def analyze_image(image):
245
  """Main analysis function"""
@@ -371,11 +470,9 @@ def apply_style_transfer(original_image, selected_transfers):
371
  os.unlink(temp_path)
372
 
373
  # Create Gradio interface
374
- with gr.Blocks(
375
- title="🎨 Intelligent Style Transfer System",
376
- theme=gr.themes.Soft()
377
- ) as demo:
378
-
379
  gr.Markdown("""
380
  # 🎨 Intelligent Multi-Attribute Style Transfer
381
 
@@ -398,8 +495,7 @@ with gr.Blocks(
398
 
399
  analyze_btn = gr.Button(
400
  "πŸ” Analyze Image",
401
- variant="primary",
402
- size="lg"
403
  )
404
 
405
  with gr.Column(scale=1):
@@ -418,8 +514,7 @@ with gr.Blocks(
418
  apply_btn = gr.Button(
419
  "✨ Apply Selected Transfers",
420
  variant="secondary",
421
- visible=False,
422
- size="lg"
423
  )
424
 
425
  with gr.Row():
@@ -433,20 +528,6 @@ with gr.Blocks(
433
  value="Select transfers and click 'Apply' to see the magic happen!"
434
  )
435
 
436
- # Example images (add some to your examples folder)
437
- gr.Examples(
438
- examples=[
439
- ["examples/example(1).jpg"],
440
- ["examples/example(2).jpg"],
441
- ["examples/example(3).jpg"],
442
- ["examples/example(4).jpg"],
443
- ["examples/example(5).jpg"],
444
- ["examples/example(6).jpg"],
445
- ],
446
- inputs=input_image,
447
- label="πŸ–ΌοΈ Try Example Images"
448
- )
449
-
450
  # Connect the interface
451
  analyze_btn.click(
452
  fn=analyze_image,
@@ -482,12 +563,11 @@ with gr.Blocks(
482
  Multiple transformations can be combined for creative effects!
483
  """)
484
 
485
- # Launch configuration for Docker deployment
486
  if __name__ == "__main__":
487
  demo.launch(
488
- server_name="0.0.0.0", # Listen on all interfaces (required for Docker)
489
- server_port=7860, # Use port 7860 (Hugging Face default)
490
- share=True, # Create shareable link for Docker environments
491
- show_error=True, # Show detailed errors for debugging
492
- enable_queue=True # Enable queuing for better stability
493
  )
 
20
  def load_classification_models(self):
21
  """Load all classification models and encoders"""
22
  print("Loading classification models...")
23
+ print(f"πŸ“‚ Looking for models in: models/classification/")
24
+
25
+ # First, let's see what's actually in the classification folder
26
+ classification_path = "models/classification"
27
+ if os.path.exists(classification_path):
28
+ print(f"πŸ“ Found classification directory")
29
+ files = os.listdir(classification_path)
30
+ print(f"πŸ“„ Available files: {files}")
31
+ else:
32
+ print(f"❌ Classification directory not found: {classification_path}")
33
+ return
34
 
35
  for category in self.categories:
36
  try:
37
  # Load model from correct path
38
  model_path = f"models/classification/{category}_model.h5"
39
  if os.path.exists(model_path):
40
+ print(f"πŸ” Loading model: {model_path}")
41
  self.models[category] = tf.keras.models.load_model(model_path)
42
+ print(f"βœ… Loaded {category} model ({os.path.getsize(model_path)/1024/1024:.1f} MB)")
43
 
44
  # Load encoder
45
  encoder_path = f"models/classification/{category}_encoder.pkl"
46
  if os.path.exists(encoder_path):
47
  with open(encoder_path, 'rb') as f:
48
  self.encoders[category] = pickle.load(f)
49
+ print(f"βœ… Loaded {category} encoder")
50
  else:
51
+ print(f"⚠️ {category} encoder not found at {encoder_path}")
52
  else:
53
+ print(f"❌ {category} model not found at {model_path}")
54
  except Exception as e:
55
  print(f"❌ Failed to load {category}: {e}")
56
+ import traceback
57
+ traceback.print_exc()
58
+
59
+ print(f"🎯 Successfully loaded {len(self.models)} classification models")
60
 
61
  def load_gan_models(self):
62
  """Load all GAN models for style transfer"""
63
  print("Loading GAN models...")
64
 
65
+ # First, let's scan what's actually in the GAN folders
66
+ gan_base_path = "models/gan"
67
+ if os.path.exists(gan_base_path):
68
+ print(f"πŸ“‚ Found GAN models directory: {gan_base_path}")
69
+ for folder in os.listdir(gan_base_path):
70
+ folder_path = os.path.join(gan_base_path, folder)
71
+ if os.path.isdir(folder_path):
72
+ print(f"πŸ“ GAN folder: {folder}")
73
+ for file in os.listdir(folder_path):
74
+ print(f" πŸ“„ {file}")
75
+
76
+ # Try multiple possible file name patterns
77
  gan_paths = {
78
+ # Day/Night models - try multiple naming patterns
79
+ 'day_to_night': [
80
+ 'models/gan/day_night/day_to_night_generator_final.keras',
81
+ 'models/gan/day_night/day_to_night_generator.keras',
82
+ 'models/gan/day_night/day_to_night.keras',
83
+ 'models/gan/day_night/generator_day_to_night.keras'
84
+ ],
85
+ 'night_to_day': [
86
+ 'models/gan/day_night/night_to_day_generator_final.keras',
87
+ 'models/gan/day_night/night_to_day_generator.keras',
88
+ 'models/gan/day_night/night_to_day.keras',
89
+ 'models/gan/day_night/generator_night_to_day.keras'
90
+ ],
91
 
92
+ # Foggy/Clear models
93
+ 'foggy_to_clear': [
94
+ 'models/gan/foggy/foggy_to_normal_generator_final.keras',
95
+ 'models/gan/foggy/foggy_to_clear_generator.keras',
96
+ 'models/gan/foggy/foggy_to_clear.keras'
97
+ ],
98
+ 'clear_to_foggy': [
99
+ 'models/gan/foggy/normal_to_foggy_generator_final.keras',
100
+ 'models/gan/foggy/clear_to_foggy_generator.keras',
101
+ 'models/gan/foggy/clear_to_foggy.keras'
102
+ ],
103
 
104
  # Japanese art models
105
+ 'photo_to_japanese': [
106
+ 'models/gan/japanese/photo_to_ukiyoe_generator.keras',
107
+ 'models/gan/japanese/photo_to_japanese_generator.keras',
108
+ 'models/gan/japanese/photo_to_japanese.keras'
109
+ ],
110
+ 'japanese_to_photo': [
111
+ 'models/gan/japanese/ukiyoe_to_photo_generator.keras',
112
+ 'models/gan/japanese/japanese_to_photo_generator.keras',
113
+ 'models/gan/japanese/japanese_to_photo.keras'
114
+ ],
115
 
116
  # Season models
117
+ 'summer_to_winter': [
118
+ 'models/gan/summer_winter/summer_to_winter_generator_final.keras',
119
+ 'models/gan/summer_winter/summer_to_winter_generator.keras',
120
+ 'models/gan/summer_winter/summer_to_winter.keras'
121
+ ],
122
+ 'winter_to_summer': [
123
+ 'models/gan/summer_winter/winter_to_summer_generator_final.keras',
124
+ 'models/gan/summer_winter/winter_to_summer_generator.keras',
125
+ 'models/gan/summer_winter/winter_to_summer.keras'
126
+ ]
127
  }
128
 
129
+ for model_name, possible_paths in gan_paths.items():
130
+ model_loaded = False
131
+ for model_path in possible_paths:
132
+ try:
133
+ if os.path.exists(model_path):
134
+ print(f"πŸ” Trying to load: {model_path}")
135
+ self.gan_models[model_name] = tf.keras.models.load_model(model_path)
136
+ print(f"βœ… Loaded GAN: {model_name} from {model_path}")
137
+ model_loaded = True
138
+ break
139
+ except Exception as e:
140
+ print(f"❌ Failed to load {model_path}: {e}")
141
+ continue
142
+
143
+ if not model_loaded:
144
+ print(f"⚠️ Could not load GAN model: {model_name}")
145
+ # Let's also scan the actual directory to see what files exist
146
+ folder_map = {
147
+ 'day_to_night': 'day_night',
148
+ 'night_to_day': 'day_night',
149
+ 'foggy_to_clear': 'foggy',
150
+ 'clear_to_foggy': 'foggy',
151
+ 'photo_to_japanese': 'japanese',
152
+ 'japanese_to_photo': 'japanese',
153
+ 'summer_to_winter': 'summer_winter',
154
+ 'winter_to_summer': 'summer_winter'
155
+ }
156
+
157
+ if model_name in folder_map:
158
+ folder_path = f"models/gan/{folder_map[model_name]}"
159
+ if os.path.exists(folder_path):
160
+ print(f" πŸ“ Available files in {folder_path}:")
161
+ for file in os.listdir(folder_path):
162
+ if file.endswith(('.keras', '.h5')):
163
+ print(f" πŸ“„ {file}")
164
+
165
+ print(f"🎯 Successfully loaded {len(self.gan_models)} GAN models")
166
 
167
  def preprocess_image_for_classification(self, image_path):
168
  """Preprocess image for classification (224x224)"""
 
311
  })
312
 
313
  # Add season transfers (these work regardless of season classification)
 
314
  transfers.extend([
315
  {
316
  'name': 'Add Winter Atmosphere',
 
329
  return transfers
330
 
331
  # Initialize classifier globally
332
+ print("πŸš€ Starting StyleTransfer App...")
333
  classifier = MultiAttributeClassifier()
334
+ print(f"🎯 Initialization complete!")
335
+ print(f" πŸ“Š Classification models loaded: {len(classifier.models)}")
336
+ print(f" 🎨 GAN models loaded: {len(classifier.gan_models)}")
337
+ if len(classifier.models) > 0:
338
+ print(f" βœ… Available categories: {list(classifier.models.keys())}")
339
+ if len(classifier.gan_models) > 0:
340
+ print(f" βœ… Available transformations: {list(classifier.gan_models.keys())}")
341
+ print("="*50)
342
 
343
  def analyze_image(image):
344
  """Main analysis function"""
 
470
  os.unlink(temp_path)
471
 
472
  # Create Gradio interface
473
+ demo = gr.Blocks(title="🎨 Intelligent Style Transfer System")
474
+
475
+ with demo:
 
 
476
  gr.Markdown("""
477
  # 🎨 Intelligent Multi-Attribute Style Transfer
478
 
 
495
 
496
  analyze_btn = gr.Button(
497
  "πŸ” Analyze Image",
498
+ variant="primary"
 
499
  )
500
 
501
  with gr.Column(scale=1):
 
514
  apply_btn = gr.Button(
515
  "✨ Apply Selected Transfers",
516
  variant="secondary",
517
+ visible=False
 
518
  )
519
 
520
  with gr.Row():
 
528
  value="Select transfers and click 'Apply' to see the magic happen!"
529
  )
530
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  # Connect the interface
532
  analyze_btn.click(
533
  fn=analyze_image,
 
563
  Multiple transformations can be combined for creative effects!
564
  """)
565
 
566
+ # Launch configuration for Hugging Face Spaces
567
  if __name__ == "__main__":
568
  demo.launch(
569
+ server_name="0.0.0.0",
570
+ server_port=7860,
571
+ share=True,
572
+ show_error=True
 
573
  )