Avmromanov commited on
Commit
ca8ddcf
Β·
1 Parent(s): 9a12af7

fix examples

Browse files
Files changed (1) hide show
  1. app.py +67 -120
app.py CHANGED
@@ -1,38 +1,41 @@
1
  import gradio as gr
2
  from transformers import pipeline
 
 
 
 
3
 
4
- # Load a model trained on car brands/makes
5
- # Using a model from the Hugging Face hub that's good at vehicle classification
6
- car_classifier = pipeline("image-classification",
7
- model="dima806/car_models_image_detection")
 
 
 
 
8
 
9
- # Alternative models you can try:
10
- # - "nickmuchi/vit-finetuned-cars-biased"
11
- # - "saltacc/anime-ai-detect"
12
- # - Or use a general object detection + custom logic
13
 
14
  def identify_car(image):
15
  if image is None:
16
  return "Please upload an image of a car"
17
 
18
  try:
19
- # Convert to RGB if necessary
20
  if image.mode != 'RGB':
21
  image = image.convert('RGB')
22
 
23
- # Get predictions
24
  predictions = car_classifier(image)
25
 
26
- # Format results
27
  result_text = "πŸš— Car Identification Results:\n\n"
 
28
 
29
- top_5 = predictions[:5] # Get top 5 predictions
30
  for i, pred in enumerate(top_5, 1):
31
  label = pred['label'].replace('_', ' ').title()
32
  confidence = pred['score']
33
  result_text += f"{i}. {label}: {confidence:.2%}\n"
34
 
35
- # Try to extract additional information
36
  result_text += f"\nπŸ” Most likely: **{top_5[0]['label'].replace('_', ' ').title()}** " \
37
  f"(confidence: {top_5[0]['score']:.2%})"
38
 
@@ -41,123 +44,67 @@ def identify_car(image):
41
  except Exception as e:
42
  return f"Error processing image: {str(e)}"
43
 
44
- def enhanced_car_analysis(image):
45
- """Enhanced version with more detailed analysis"""
46
- if image is None:
47
- return "Please upload an image of a car"
 
 
48
 
49
  try:
50
- # Get basic predictions
51
- predictions = car_classifier(image)
52
-
53
- # Create detailed analysis
54
- analysis = "πŸš— **Detailed Car Analysis**\n\n"
55
-
56
- # Top prediction
57
- top_pred = predictions[0]
58
- brand = top_pred['label'].replace('_', ' ').title()
59
- confidence = top_pred['score']
60
-
61
- analysis += f"**Primary Identification:**\n"
62
- analysis += f"β€’ Brand: {brand}\n"
63
- analysis += f"β€’ Confidence: {confidence:.2%}\n\n"
64
-
65
- # Top 3 alternatives
66
- analysis += "**Alternative Possibilities:**\n"
67
- for i, pred in enumerate(predictions[1:4], 2):
68
- alt_brand = pred['label'].replace('_', ' ').title()
69
- alt_conf = pred['score']
70
- analysis += f"{i}. {alt_brand} ({alt_conf:.2%})\n"
71
-
72
- # Confidence level interpretation
73
- if confidence > 0.8:
74
- analysis += f"\nβœ… **High confidence** - Very likely a {brand}"
75
- elif confidence > 0.6:
76
- analysis += f"\n⚠️ **Moderate confidence** - Probably a {brand}"
77
- else:
78
- analysis += f"\n❓ **Low confidence** - Could be a {brand} or similar brand"
79
-
80
- # Tips for better identification
81
- analysis += "\n\n**πŸ’‘ Tips for better identification:**"
82
- analysis += "\nβ€’ Use clear, front/side views of the car"
83
- analysis += "\nβ€’ Ensure good lighting and focus"
84
- analysis += "\nβ€’ Avoid images with multiple cars"
85
- analysis += "\nβ€’ Crop close to the car for better accuracy"
86
-
87
- return analysis
88
-
89
  except Exception as e:
90
- return f"Error processing image: {str(e)}"
91
-
92
- # Create a more advanced interface with tabs
93
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
94
- gr.Markdown("# πŸš— Car Brand & Model Identifier")
95
- gr.Markdown("Upload a photo of a car to identify its brand and model!")
96
 
97
- with gr.Tab("Quick Identification"):
98
- gr.Markdown("### Fast car brand identification")
99
- with gr.Row():
100
- with gr.Column():
101
- image_input = gr.Image(label="Upload Car Photo", type="pil")
102
- quick_btn = gr.Button("Identify Car", variant="primary")
103
- with gr.Column():
104
- quick_output = gr.Textbox(label="Identification Results", lines=8)
 
 
105
 
106
- with gr.Tab("Detailed Analysis"):
107
- gr.Markdown("### Comprehensive car analysis")
108
- with gr.Row():
109
- with gr.Column():
110
- detail_input = gr.Image(label="Upload Car Photo", type="pil")
111
- detail_btn = gr.Button("Analyze Car", variant="primary")
112
- with gr.Column():
113
- detail_output = gr.Textbox(label="Detailed Analysis", lines=15)
114
 
115
- with gr.Tab("About"):
116
- gr.Markdown("""
117
- ## About This Car Identifier
118
-
119
- **How it works:**
120
- - Uses a deep learning model trained on car images
121
- - Identifies car brands/makes from photographs
122
- - Provides confidence scores for each prediction
123
-
124
- **Best practices:**
125
- - Use clear, well-lit photos
126
- - Front or side views work best
127
- - Avoid blurry or distant shots
128
- - Single car images yield better results
129
-
130
- **Supported brands include:** Toyota, Honda, Ford, BMW, Mercedes, Audi,
131
- Volkswagen, Nissan, Chevrolet, Hyundai, and many more!
132
- """)
133
-
134
- # Examples section
135
- gr.Markdown("### Example Car Images")
136
  gr.Examples(
137
- examples=[
138
- ["https://cdn.pixabay.com/photo/2015/01/19/13/51/car-604019_1280.jpg"], # Audi
139
- ["https://cdn.pixabay.com/photo/2012/11/02/13/02/car-63930_1280.jpg"], # Ford Mustang
140
- ["https://cdn.pixabay.com/photo/2015/09/02/12/25/bmw-918408_1280.jpg"], # BMW
141
- ["https://cdn.pixabay.com/photo/2014/09/07/22/34/car-tire-438467_1280.jpg"] # Mercedes
142
- ],
143
  inputs=image_input,
144
- outputs=quick_output,
145
  fn=identify_car,
146
  cache_examples=True
147
  )
148
 
149
- # Connect buttons
150
- quick_btn.click(identify_car, inputs=image_input, outputs=quick_output)
151
- detail_btn.click(enhanced_car_analysis, inputs=detail_input, outputs=detail_output)
152
-
153
- # For better performance on Hugging Face Spaces
154
- def load_model():
155
- # This will cache the model loading
156
- return pipeline("image-classification",
157
- model="dima806/car_brand_classification")
158
-
159
- # Pre-load the model when the app starts
160
- car_classifier = load_model()
161
 
162
- if __name__ == "__main__":
163
- demo.launch(share=True)
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ from datasets import load_dataset
4
+ from PIL import Image
5
+ import requests
6
+ import io
7
 
8
+ # Load your custom dataset
9
+ def load_my_dataset():
10
+ try:
11
+ dataset = load_dataset("Avmromanov/tripoexamples")
12
+ return dataset
13
+ except Exception as e:
14
+ print(f"Error loading dataset: {e}")
15
+ return None
16
 
17
+ # Load car classification model
18
+ car_classifier = pipeline("image-classification",
19
+ model="dima806/car_brand_classification")
 
20
 
21
  def identify_car(image):
22
  if image is None:
23
  return "Please upload an image of a car"
24
 
25
  try:
 
26
  if image.mode != 'RGB':
27
  image = image.convert('RGB')
28
 
 
29
  predictions = car_classifier(image)
30
 
 
31
  result_text = "πŸš— Car Identification Results:\n\n"
32
+ top_5 = predictions[:5]
33
 
 
34
  for i, pred in enumerate(top_5, 1):
35
  label = pred['label'].replace('_', ' ').title()
36
  confidence = pred['score']
37
  result_text += f"{i}. {label}: {confidence:.2%}\n"
38
 
 
39
  result_text += f"\nπŸ” Most likely: **{top_5[0]['label'].replace('_', ' ').title()}** " \
40
  f"(confidence: {top_5[0]['score']:.2%})"
41
 
 
44
  except Exception as e:
45
  return f"Error processing image: {str(e)}"
46
 
47
+ def get_dataset_examples(dataset, num_examples=3):
48
+ """Extract example images from the dataset"""
49
+ examples = []
50
+
51
+ if dataset is None:
52
+ return examples
53
 
54
  try:
55
+ # Adjust this based on your dataset structure
56
+ train_data = dataset['train']
57
+
58
+ for i in range(min(num_examples, len(train_data))):
59
+ example = train_data[i]
60
+
61
+ # The structure depends on your dataset - adjust accordingly
62
+ if 'image' in example:
63
+ # If images are stored in the dataset
64
+ examples.append(example['image'])
65
+ elif 'url' in example:
66
+ # If URLs are provided
67
+ examples.append(example['url'])
68
+ elif 'path' in example:
69
+ # If file paths are provided
70
+ examples.append(example['path'])
71
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  except Exception as e:
73
+ print(f"Error extracting examples: {e}")
 
 
 
 
 
74
 
75
+ return examples
76
+
77
+ # Load your dataset
78
+ my_dataset = load_my_dataset()
79
+ dataset_examples = get_dataset_examples(my_dataset, num_examples=4)
80
+
81
+ # Create the interface
82
+ with gr.Blocks() as demo:
83
+ gr.Markdown("# πŸš— Car Identifier with My Dataset")
84
+ gr.Markdown("Using examples from: **Avmromanov/tripoexamples**")
85
 
86
+ with gr.Row():
87
+ with gr.Column():
88
+ image_input = gr.Image(label="Upload Car Photo", type="pil")
89
+ identify_btn = gr.Button("Identify Car", variant="primary")
90
+ with gr.Column():
91
+ output_text = gr.Textbox(label="Results", lines=10)
 
 
92
 
93
+
94
+ gr.Markdown(f"### Dataset Examples (showing {len(dataset_examples)} samples)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  gr.Examples(
96
+ examples=dataset_examples,
 
 
 
 
 
97
  inputs=image_input,
98
+ outputs=output_text,
99
  fn=identify_car,
100
  cache_examples=True
101
  )
102
 
103
+ gr.Markdown("""
104
+ **Dataset Information:**
105
+ - Name: tripoexamples
106
+ - Author: Avmromanov
107
+ - Type: Car images for identification
108
+ """)
 
 
 
 
 
 
109
 
110
+ demo.launch()