dhruvsaxena11 commited on
Commit
715ba6c
·
verified ·
1 Parent(s): 7276b88

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import random
5
+ from datetime import datetime, timedelta
6
+ from transformers import pipeline, AutoProcessor, Qwen2VLForConditionalGeneration, Blip2ForConditionalGeneration
7
+ from PIL import Image
8
+ import torch
9
+
10
+ # Function to simulate sensor data
11
+ def generate_sensor_data(num_entries):
12
+ data = []
13
+ timestamp = datetime.now()
14
+ for _ in range(num_entries):
15
+ entry = {
16
+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
17
+ "engine_temp": random.randint(80, 110),
18
+ "oil_pressure": random.randint(15, 50),
19
+ "tire_pressure": random.randint(29, 35),
20
+ "battery_voltage": round(random.uniform(11.0, 13.0), 1)
21
+ }
22
+ # Introduce anomalies
23
+ if random.random() < 0.1:
24
+ entry["engine_temp"] = random.randint(105, 120)
25
+ if random.random() < 0.1:
26
+ entry["oil_pressure"] = random.randint(10, 20)
27
+ if random.random() < 0.05:
28
+ entry["battery_voltage"] = round(random.uniform(10.5, 11.5), 1)
29
+ data.append(entry)
30
+ timestamp += timedelta(minutes=5)
31
+ return pd.DataFrame(data)
32
+
33
+ # Generate sensor data
34
+ sensor_data = generate_sensor_data(10)
35
+
36
+ # Plot sensor data
37
+ def plot_sensor_data(df):
38
+ timestamps = pd.to_datetime(df["timestamp"])
39
+ fig, axs = plt.subplots(2, 2, figsize=(14, 10))
40
+ fig.suptitle('Sensor Data', fontsize=16)
41
+
42
+ thresholds = {"engine_temp": 100, "oil_pressure": 25, "tire_pressure": 28, "battery_voltage": 11.5}
43
+
44
+ axs[0, 0].plot(timestamps, df["engine_temp"], color='red')
45
+ axs[0, 0].axhline(y=thresholds["engine_temp"], color='green', linestyle='--')
46
+ axs[0, 0].set_title("Engine Temperature (°C)")
47
+
48
+ axs[0, 1].plot(timestamps, df["oil_pressure"], color='blue')
49
+ axs[0, 1].axhline(y=thresholds["oil_pressure"], color='orange', linestyle='--')
50
+ axs[0, 1].set_title("Oil Pressure (psi)")
51
+
52
+ axs[1, 0].plot(timestamps, df["tire_pressure"], color='green')
53
+ axs[1, 0].axhline(y=thresholds["tire_pressure"], color='purple', linestyle='--')
54
+ axs[1, 0].set_title("Tire Pressure (psi)")
55
+
56
+ axs[1, 1].plot(timestamps, df["battery_voltage"], color='black')
57
+ axs[1, 1].axhline(y=thresholds["battery_voltage"], color='brown', linestyle='--')
58
+ axs[1, 1].set_title("Battery Voltage (V)")
59
+
60
+ plt.tight_layout()
61
+ fig_path = "sensor_plot.png"
62
+ plt.savefig(fig_path)
63
+ return fig_path
64
+
65
+ # Initialize models
66
+ # def load_models():
67
+ # vqa_model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-flan-t5-xl")
68
+ # damage_model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
69
+ # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
70
+ # return vqa_model, damage_model, processor
71
+
72
+ # vqa_model, damage_model, processor = load_models()
73
+
74
+ # Generate recommendations
75
+ def analyze_data(image, plot_path):
76
+ # Damage analysis
77
+ if image:
78
+ messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": "Describe the damage."}]}]
79
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
80
+ inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt")
81
+ inputs = inputs.to("cuda" if torch.cuda.is_available() else "cpu")
82
+ output_ids = damage_model.generate(**inputs, max_new_tokens=128)
83
+ damage_output = processor.batch_decode(output_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
84
+ else:
85
+ damage_output = "No image uploaded."
86
+
87
+ # Graph analysis
88
+ vqa_result = vqa_model(image=plot_path, question="What anomalies or patterns can be observed?")
89
+ graph_analysis = vqa_result[0]["answer"]
90
+
91
+ # Recommendations
92
+ recommendations = f"Recommendations based on analysis:\n\n1. {graph_analysis}\n\n2. {damage_output}"
93
+ return recommendations, plot_path, graph_analysis
94
+
95
+ # Gradio UI
96
+ with gr.Blocks(css=".output-text { font-family: 'Arial'; color: #222; font-size: 1rem; }") as app:
97
+ gr.Markdown("# 🚗 Car Health Report Generation using Generative AI")
98
+ with gr.Row():
99
+ car_image = gr.Image(type="pil", label="Upload Car Part Damage Image")
100
+ with gr.Row():
101
+ display_graph = gr.Image(plot_sensor_data(sensor_data), label="Sensor Data Over Time")
102
+ recommendations = gr.Textbox(label="Analysis & Recommendations", placeholder="Insights will appear here...")
103
+ graph_insights = gr.Textbox(label="Graph Insights", placeholder="Graph insights will appear here...")
104
+ data_table = gr.Dataframe(sensor_data, label="Generated Sensor Data (Table View)", row_count=(10, "fixed"), interactive=False)
105
+
106
+ # Realistic colors and UI layout for a polished look
107
+ car_image.change(fn=analyze_data, inputs=[car_image, display_graph], outputs=[recommendations, display_graph, graph_insights])
108
+
109
+ app.launch()