MODLI commited on
Commit
f69ea27
·
verified ·
1 Parent(s): fd7501f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -74
app.py CHANGED
@@ -1,111 +1,125 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- from PIL import Image
4
  import numpy as np
 
5
 
6
- # Liste des catégories de vêtements
7
  FASHION_CATEGORIES = [
8
- "t-shirt", "long sleeve shirt", "short sleeve shirt",
9
- "sleeveless shirt", "polo shirt", "sweatshirt",
10
- "hoodie", "sweater", "cardigan", "jacket", "coat",
11
- "blazer", "dress", "long dress", "short dress",
12
- "skirt", "long skirt", "short skirt", "jeans",
13
- "pants", "trousers", "shorts", "leggings",
14
- "sports shoes", "sneakers", "boots", "heels", "sandals"
15
  ]
16
 
17
- # Charger le modèle de classification
18
- print("Loading classification model...")
19
- class_pipe = pipeline(
20
- "zero-shot-image-classification",
21
- model="openai/clip-vit-base-patch32"
22
- )
23
- print("Model loaded successfully!")
24
 
25
- def classify_image(input_image):
26
- """Fonction simple pour classifier les images"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  try:
28
- if input_image is None:
29
- return "Please upload an image first"
30
 
31
- # Convertir en format PIL si nécessaire
32
- if isinstance(input_image, np.ndarray):
33
- input_image = Image.fromarray(input_image)
34
 
35
- # Redimensionner pour de meilleures performances
36
- input_image = input_image.resize((224, 224))
37
-
38
- # Classification
39
  predictions = class_pipe(
40
- input_image,
41
  candidate_labels=FASHION_CATEGORIES,
42
- hypothesis_template="This is a photo of {}"
 
43
  )
44
 
45
- # Formater les résultats
46
- result_text = "👗 Classification Results:\n\n"
47
- for i, pred in enumerate(predictions[:5]):
48
- result_text += f"{i+1}. {pred['label']}: {pred['score']*100:.1f}%\n"
 
 
 
 
 
 
49
 
50
- return result_text
51
 
52
  except Exception as e:
53
- return f"Error: {str(e)}"
54
 
55
- # Interface Gradio simple
56
- with gr.Blocks(title="Fashion Classifier", theme=gr.themes.Soft()) as demo:
57
- gr.Markdown("""
58
- # 👗 Fashion Category Classifier
59
- Upload a picture of clothing to classify it.
60
- """)
61
 
62
  with gr.Row():
63
  with gr.Column():
64
- image_input = gr.Image(
65
- label="📤 Upload Clothing Image",
66
- type="pil",
67
- height=300
68
- )
69
 
70
- classify_btn = gr.Button(
71
- "🔍 Classify Image",
72
- variant="primary",
73
- size="lg"
74
- )
75
-
76
  with gr.Column():
77
- output_text = gr.Textbox(
78
- label="📊 Results",
79
- lines=8,
80
- interactive=False
81
- )
82
 
83
  # Instructions
84
  gr.Markdown("""
85
- ### 📝 How to use:
86
- 1. Upload an image of a clothing item
87
- 2. Click the 'Classify Image' button
88
- 3. See the classification results
 
 
89
  """)
90
 
91
- # Lier le bouton à la fonction
92
- classify_btn.click(
93
- fn=classify_image,
94
  inputs=image_input,
95
- outputs=output_text
96
  )
97
 
98
- # Ajouter aussi le changement sur l'upload
99
  image_input.upload(
100
- fn=classify_image,
101
  inputs=image_input,
102
- outputs=output_text
103
  )
104
 
105
- # Lancer l'application
106
  if __name__ == "__main__":
107
- demo.launch(
108
- server_name="0.0.0.0",
109
- server_port=7860,
110
- share=False
111
- )
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ from PIL import Image, ImageOps, ImageFilter
4
  import numpy as np
5
+ import cv2
6
 
7
+ # Catégories précises et distinctes
8
  FASHION_CATEGORIES = [
9
+ "t-shirt", "button-down shirt", "polo shirt",
10
+ "sweatshirt", "hoodie", "sweater",
11
+ "jacket", "coat", "blazer",
12
+ "dress", "long dress", "short dress",
13
+ "skirt", "long skirt", "short skirt",
14
+ "jeans", "pants", "shorts",
15
+ "sneakers", "boots", "heels", "sandals"
16
  ]
17
 
18
+ # Chargement des modèles
19
+ print("🔧 Loading models...")
20
+ seg_pipe = pipeline("image-segmentation", model="mattmdjaga/segformer_b2_clothes")
21
+ class_pipe = pipeline("zero-shot-image-classification", model="openai/clip-vit-base-patch32")
22
+ print("✅ Models loaded!")
 
 
23
 
24
+ def preprocess_image(image):
25
+ """Prétraitement avancé de l'image"""
26
+ # Conversion en numpy array si nécessaire
27
+ if isinstance(image, np.ndarray):
28
+ image = Image.fromarray(image)
29
+
30
+ # Réduction de taille pour meilleures performances
31
+ image = image.resize((512, 512))
32
+
33
+ return image
34
+
35
+ def remove_background(image):
36
+ """Suppression professionnelle de l'arrière-plan"""
37
+ # Segmentation
38
+ segments = seg_pipe(image)
39
+ if not segments:
40
+ return image
41
+
42
+ # Trouver le vêtement principal
43
+ largest_segment = max(segments, key=lambda x: np.sum(x['mask']))
44
+ mask = np.array(largest_segment['mask'])
45
+
46
+ # Application du masque
47
+ image_np = np.array(image)
48
+ masked_image = np.zeros_like(image_np)
49
+ masked_image[mask > 0] = image_np[mask > 0]
50
+
51
+ return Image.fromarray(masked_image)
52
+
53
+ def classify_fashion(image):
54
+ """Classification précise"""
55
  try:
56
+ # Préprocessing
57
+ processed_image = preprocess_image(image)
58
 
59
+ # Suppression de l'arrière-plan
60
+ isolated_image = remove_background(processed_image)
 
61
 
62
+ # Classification avec paramètres optimisés
 
 
 
63
  predictions = class_pipe(
64
+ isolated_image,
65
  candidate_labels=FASHION_CATEGORIES,
66
+ hypothesis_template="a clear photo of {}",
67
+ multi_label=False
68
  )
69
 
70
+ # Filtrage des résultats (seulement > 10% de confiance)
71
+ filtered_predictions = [p for p in predictions if p['score'] > 0.1]
72
+
73
+ if not filtered_predictions:
74
+ return "❌ No confident prediction. Try a clearer image.", isolated_image
75
+
76
+ # Formatage des résultats
77
+ result_text = "🎯 **Top Predictions:**\n\n"
78
+ for i, pred in enumerate(filtered_predictions[:3]):
79
+ result_text += f"{i+1}. **{pred['label']}**: {pred['score']*100:.1f}%\n"
80
 
81
+ return result_text, isolated_image
82
 
83
  except Exception as e:
84
+ return f"Error: {str(e)}", None
85
 
86
+ # Interface améliorée
87
+ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px;}") as demo:
88
+ gr.Markdown("# 👗 **Fashion AI - Professional Classifier**")
 
 
 
89
 
90
  with gr.Row():
91
  with gr.Column():
92
+ gr.Markdown("### 📤 Upload Image")
93
+ image_input = gr.Image(type="pil", label="Clothing Image")
94
+ process_btn = gr.Button("🚀 Analyze Image", variant="primary")
 
 
95
 
 
 
 
 
 
 
96
  with gr.Column():
97
+ gr.Markdown("### 📊 Results")
98
+ output_text = gr.Markdown(label="Analysis")
99
+ output_image = gr.Image(label="Processed Image", interactive=False)
 
 
100
 
101
  # Instructions
102
  gr.Markdown("""
103
+ ### 💡 **Pro Tips for Best Results:**
104
+ - Use clear, well-lit photos
105
+ - Center the clothing item
106
+ - Use plain backgrounds when possible
107
+ - ✅ Avoid multiple items in one photo
108
+ - ❌ Don't use blurry or dark images
109
  """)
110
 
111
+ # Events
112
+ process_btn.click(
113
+ fn=classify_fashion,
114
  inputs=image_input,
115
+ outputs=[output_text, output_image]
116
  )
117
 
 
118
  image_input.upload(
119
+ fn=classify_fashion,
120
  inputs=image_input,
121
+ outputs=[output_text, output_image]
122
  )
123
 
 
124
  if __name__ == "__main__":
125
+ demo.launch()