Msaqibsharif commited on
Commit
ad4dc06
·
verified ·
1 Parent(s): 9e361ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -101
app.py CHANGED
@@ -1,101 +1,99 @@
1
- # Import necessary libraries
2
- import os
3
- import requests
4
- from PIL import Image
5
- import torch
6
- from transformers import AutoImageProcessor, AutoModelForImageClassification
7
- import gradio as gr
8
- import openai
9
-
10
- # Load the Hugging Face model for car damage detection
11
- model_name = "beingamit99/car_damage_detection"
12
- processor = AutoImageProcessor.from_pretrained(model_name)
13
- model = AutoModelForImageClassification.from_pretrained(model_name)
14
-
15
- # Set your OpenAI API key
16
- openai_api_key = os.getenv("OpenAI4oMini")
17
-
18
- client = openai.OpenAI(api_key = openai_api_key)
19
-
20
- # Dropdown Options
21
- car_companies = ["Select", "Toyota", "Honda", "Ford", "BMW", "Mercedes", "Audi", "Hyundai", "Kia", "Nissan"]
22
- car_models = [
23
- "Select", # Default option
24
- "Corolla", "Camry", "RAV4", "Highlander", # Toyota
25
- "Civic", "Accord", "CR-V", "Pilot", # Honda
26
- "Fiesta", "Focus", "Explorer", "Mustang", # Ford
27
- "3 Series", "5 Series", "X3", "X5", # BMW
28
- "C-Class", "E-Class", "GLC", "GLE", # Mercedes
29
- "A3", "A4", "Q5", "Q7", # Audi
30
- "Elantra", "Sonata", "Tucson", "Santa Fe", # Hyundai
31
- "Rio", "Optima", "Sportage", "Sorento", # Kia
32
- "Sentra", "Altima", "Rogue", "Murano" # Nissan
33
- ]
34
-
35
- years = [str(year) for year in range(2000, 2025)]
36
- countries = ["Select", "Pakistan", "USA", "UK", "Canada", "Australia", "Germany", "India", "Japan"]
37
-
38
- # Function to Estimate Repair Cost using GPT-4.0 Mini
39
- def estimate_repair_cost(damage_type, company, model, year, country):
40
- prompt = (
41
- f"Estimate the repair cost for {damage_type} on a {year} {company} {model} in {country}. "
42
- f"Provide the approximate total cost in local currency with your confidence level, concisely in 2 lines."
43
- )
44
-
45
- try:
46
- response = client.chat.completions.create(
47
- model="gpt-4o-mini",
48
- messages=[
49
- {"role": "system", "content": "You are an expert in car repair cost estimation."},
50
- {"role": "user", "content": prompt}
51
- ],
52
- temperature=0.5,
53
- max_tokens=100
54
- )
55
- return response.choices[0].message.content.strip()
56
- except Exception as e:
57
- print(f"Error in GPT-4o API call: {e}")
58
- return f"Error: {e}"
59
-
60
- # Function to Detect Car Damage from Image using Hugging Face Model
61
- def detect_damage(image):
62
- inputs = processor(images=image, return_tensors="pt")
63
- with torch.no_grad():
64
- outputs = model(**inputs)
65
- probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
66
- confidences, predicted_class = torch.max(probs, dim=-1)
67
- predicted_label = model.config.id2label[predicted_class.item()]
68
- return predicted_label, confidences.item()
69
-
70
- # Function to Process Image and Get Results
71
- def process_image(image, company, model, year, country):
72
- damage_type, confidence = detect_damage(image)
73
- cost_estimate = estimate_repair_cost(damage_type, company, model, year, country)
74
-
75
- result = {
76
- "Major Detected Damage": damage_type,
77
- "Confidence": f"{confidence * 100:.2f}%",
78
- "Estimated Repair Cost": cost_estimate
79
- }
80
- return result
81
-
82
- # Gradio Interface
83
- with gr.Blocks() as interface:
84
- gr.Markdown("# Car Damage Detection and Cost Estimation")
85
- gr.Markdown("Upload an image of a damaged car to detect the type of damage and estimate the repair cost.")
86
-
87
- with gr.Row():
88
- with gr.Column():
89
- image_input = gr.Image(type="pil", label="Upload Car Image")
90
- company_input = gr.Dropdown(choices=car_companies, label="Car Company", value="Select")
91
- model_input = gr.Dropdown(choices=car_models, label="Car Model", value="Select")
92
- year_input = gr.Dropdown(choices=years, label="Year of Manufacture", value=years[-1])
93
- country_input = gr.Dropdown(choices=countries, label="Your Country", value="Select")
94
-
95
- submit_button = gr.Button("Estimate Repair Cost")
96
- output = gr.JSON(label="Result")
97
-
98
- submit_button.click(process_image, inputs=[image_input, company_input, model_input, year_input, country_input], outputs=output)
99
-
100
- # Launch the Gradio Interface
101
- interface.launch()
 
1
+ # Import necessary libraries
2
+ import os
3
+ import torch
4
+ from PIL import Image
5
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
6
+ import gradio as gr
7
+ import openai
8
+
9
+ # Load the Hugging Face model for car damage detection
10
+ model_name = "beingamit99/car_damage_detection"
11
+ processor = AutoImageProcessor.from_pretrained(model_name)
12
+ model = AutoModelForImageClassification.from_pretrained(model_name)
13
+
14
+ # Set your OpenAI API key from environment variable
15
+ openai_api_key = os.getenv("OPENAI_API_KEY")
16
+ openai.api_key = openai_api_key
17
+
18
+ # Dropdown Options
19
+ car_companies = ["Select", "Toyota", "Honda", "Ford", "BMW", "Mercedes", "Audi", "Hyundai", "Kia", "Nissan"]
20
+ car_models = [
21
+ "Select", # Default option
22
+ "Corolla", "Camry", "RAV4", "Highlander", # Toyota
23
+ "Civic", "Accord", "CR-V", "Pilot", # Honda
24
+ "Fiesta", "Focus", "Explorer", "Mustang", # Ford
25
+ "3 Series", "5 Series", "X3", "X5", # BMW
26
+ "C-Class", "E-Class", "GLC", "GLE", # Mercedes
27
+ "A3", "A4", "Q5", "Q7", # Audi
28
+ "Elantra", "Sonata", "Tucson", "Santa Fe", # Hyundai
29
+ "Rio", "Optima", "Sportage", "Sorento", # Kia
30
+ "Sentra", "Altima", "Rogue", "Murano" # Nissan
31
+ ]
32
+
33
+ years = [str(year) for year in range(2000, 2025)]
34
+ countries = ["Select", "Pakistan", "USA", "UK", "Canada", "Australia", "Germany", "India", "Japan"]
35
+
36
+ # Function to Estimate Repair Cost using GPT-4.0 Mini
37
+ def estimate_repair_cost(damage_type, company, model, year, country):
38
+ prompt = (
39
+ f"Estimate the repair cost for {damage_type} on a {year} {company} {model} in {country}. "
40
+ f"Provide the approximate total cost in local currency with your confidence level, concisely in 2 lines."
41
+ )
42
+
43
+ try:
44
+ response = openai.ChatCompletion.create(
45
+ model="gpt-4o-mini",
46
+ messages=[
47
+ {"role": "system", "content": "You are an expert in car repair cost estimation."},
48
+ {"role": "user", "content": prompt}
49
+ ],
50
+ temperature=0.5,
51
+ max_tokens=100
52
+ )
53
+ return response['choices'][0]['message']['content'].strip()
54
+ except Exception as e:
55
+ print(f"Error in GPT-4.0 API call: {e}")
56
+ return f"Error: {e}"
57
+
58
+ # Function to Detect Car Damage from Image using Hugging Face Model
59
+ def detect_damage(image):
60
+ inputs = processor(images=image, return_tensors="pt")
61
+ with torch.no_grad():
62
+ outputs = model(**inputs)
63
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
64
+ confidences, predicted_class = torch.max(probs, dim=-1)
65
+ predicted_label = model.config.id2label[predicted_class.item()]
66
+ return predicted_label, confidences.item()
67
+
68
+ # Function to Process Image and Get Results
69
+ def process_image(image, company, model, year, country):
70
+ damage_type, confidence = detect_damage(image)
71
+ cost_estimate = estimate_repair_cost(damage_type, company, model, year, country)
72
+
73
+ result = {
74
+ "Major Detected Damage": damage_type,
75
+ "Confidence": f"{confidence * 100:.2f}%",
76
+ "Estimated Repair Cost": cost_estimate
77
+ }
78
+ return result
79
+
80
+ # Gradio Interface
81
+ with gr.Blocks() as interface:
82
+ gr.Markdown("# Car Damage Detection and Cost Estimation")
83
+ gr.Markdown("Upload an image of a damaged car to detect the type of damage and estimate the repair cost.")
84
+
85
+ with gr.Row():
86
+ with gr.Column():
87
+ image_input = gr.Image(type="pil", label="Upload Car Image")
88
+ company_input = gr.Dropdown(choices=car_companies, label="Car Company", value="Select")
89
+ model_input = gr.Dropdown(choices=car_models, label="Car Model", value="Select")
90
+ year_input = gr.Dropdown(choices=years, label="Year of Manufacture", value=years[-1])
91
+ country_input = gr.Dropdown(choices=countries, label="Your Country", value="Select")
92
+
93
+ submit_button = gr.Button("Estimate Repair Cost")
94
+ output = gr.JSON(label="Result")
95
+
96
+ submit_button.click(process_image, inputs=[image_input, company_input, model_input, year_input, country_input], outputs=output)
97
+
98
+ # Launch the Gradio Interface
99
+ interface.launch()