VishalD1234 commited on
Commit
495550d
·
verified ·
1 Parent(s): 852d6ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +242 -57
app.py CHANGED
@@ -1,17 +1,171 @@
1
  import gradio as gr
 
 
2
  import torch
3
- from PIL import Image
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
  from transformers import BitsAndBytesConfig
6
- import torchvision.transforms as transforms
7
 
8
- # Model configuration
9
  MODEL_PATH = "THUDM/cogvlm2-llama3-caption"
10
  DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
11
  TORCH_TYPE = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else torch.float16
12
 
13
- # Load Model and Tokenizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def load_model():
 
15
  quantization_config = BitsAndBytesConfig(
16
  load_in_4bit=True,
17
  bnb_4bit_compute_dtype=TORCH_TYPE,
@@ -27,50 +181,17 @@ def load_model():
27
  quantization_config=quantization_config,
28
  device_map="auto"
29
  ).eval()
 
30
  return model, tokenizer
31
 
32
- model, tokenizer = load_model()
33
-
34
- # Delay Reasons for Each Manufacturing Step
35
- DELAY_REASONS = {
36
- "Step 1": ["Delay in Bead Insertion", "Lack of raw material"],
37
- "Step 2": ["Inner Liner Adjustment by Technician", "Person rebuilding defective Tire Sections"],
38
- "Step 3": ["Manual Adjustment in Ply1 apply", "Technician repairing defective Tire Sections"],
39
- "Step 4": ["Delay in Bead set", "Lack of raw material"],
40
- "Step 5": ["Delay in Turnup", "Lack of raw material"],
41
- "Step 6": ["Person Repairing sidewall", "Person rebuilding defective Tire Sections"],
42
- "Step 7": ["Delay in sidewall stitching", "Lack of raw material"],
43
- "Step 8": ["No person available to load Carcass", "No person available to collect tire"]
44
- }
45
-
46
- def load_image(image_data):
47
- """Preprocess the input image for model compatibility."""
48
- transform = transforms.Compose([
49
- transforms.Resize((224, 224)),
50
- transforms.ToTensor(),
51
- transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
52
- ])
53
- image = Image.open(image_data).convert("RGB")
54
- image_tensor = transform(image).unsqueeze(0).to(DEVICE, dtype=TORCH_TYPE)
55
- return image_tensor
56
-
57
- def get_analysis_prompt(step_number):
58
- """Generates the analysis prompt for the given step."""
59
- delay_reasons = DELAY_REASONS.get(step_number, [])
60
- prompt = f"""
61
- You are an AI expert analyzing tire manufacturing steps.
62
- This is Step {step_number}. Identify the most likely cause of delay based on visual evidence.
63
- Possible Delay Reasons: {', '.join(delay_reasons)}
64
- Provide the reason and supporting evidence.
65
- """
66
- return prompt
67
-
68
- def predict(prompt, image_tensor, temperature=0.3):
69
- """Generates predictions based on the image and textual prompt."""
70
  inputs = model.build_conversation_input_ids(
71
  tokenizer=tokenizer,
72
  query=prompt,
73
- images=[image_tensor],
74
  history=[],
75
  template_version='chat'
76
  )
@@ -79,11 +200,11 @@ def predict(prompt, image_tensor, temperature=0.3):
79
  'input_ids': inputs['input_ids'].unsqueeze(0).to(DEVICE),
80
  'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to(DEVICE),
81
  'attention_mask': inputs['attention_mask'].unsqueeze(0).to(DEVICE),
82
- 'images': [[inputs['images'][0]]],
83
  }
84
 
85
  gen_kwargs = {
86
- "max_new_tokens": 1024,
87
  "pad_token_id": 128002,
88
  "top_k": 1,
89
  "do_sample": False,
@@ -93,33 +214,84 @@ def predict(prompt, image_tensor, temperature=0.3):
93
 
94
  with torch.no_grad():
95
  outputs = model.generate(**inputs, **gen_kwargs)
 
96
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
97
  return response
98
 
99
- def inference(image, step_number):
100
- """Handles the inference process."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  try:
102
- if not image:
103
- return "Please upload an image."
104
 
105
- image_tensor = load_image(image)
106
  prompt = get_analysis_prompt(step_number)
107
- response = predict(prompt, image_tensor)
 
 
108
  return response
109
  except Exception as e:
110
  return f"An error occurred during analysis: {str(e)}"
111
 
112
- # Gradio Interface
113
  def create_interface():
 
114
  with gr.Blocks() as demo:
115
  gr.Markdown("""
116
- # Manufacturing Step Analysis System (Image Input)
117
- Upload an image and select the manufacturing step to analyze potential delays.
 
118
  """)
119
 
120
  with gr.Row():
121
  with gr.Column():
122
- image_input = gr.Image(label="Upload Manufacturing Image", type="file")
123
  step_number = gr.Dropdown(
124
  choices=[f"Step {i}" for i in range(1, 9)],
125
  label="Manufacturing Step"
@@ -129,13 +301,26 @@ def create_interface():
129
  with gr.Column():
130
  output = gr.Textbox(label="Analysis Result", lines=10)
131
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  analyze_btn.click(
133
  fn=inference,
134
- inputs=[image_input, step_number],
135
  outputs=[output]
136
  )
 
137
  return demo
138
 
139
  if __name__ == "__main__":
140
  demo = create_interface()
141
- demo.queue().launch(share=True)
 
1
  import gradio as gr
2
+ import io
3
+ import numpy as np
4
  import torch
5
+ from decord import cpu, VideoReader, bridge
6
  from transformers import AutoModelForCausalLM, AutoTokenizer
7
  from transformers import BitsAndBytesConfig
 
8
 
 
9
  MODEL_PATH = "THUDM/cogvlm2-llama3-caption"
10
  DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
11
  TORCH_TYPE = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else torch.float16
12
 
13
+ # Delay Reasons for Each Manufacturing Step
14
+ DELAY_REASONS = {
15
+ "Step 1": ["Delay in Bead Insertion", "Lack of raw material"],
16
+ "Step 2": ["Inner Liner Adjustment by Technician", "Person rebuilding defective Tire Sections"],
17
+ "Step 3": ["Manual Adjustment in Ply1 apply", "Technician repairing defective Tire Sections"],
18
+ "Step 4": ["Delay in Bead set", "Lack of raw material"],
19
+ "Step 5": ["Delay in Turnup", "Lack of raw material"],
20
+ "Step 6": ["Person Repairing sidewall", "Person rebuilding defective Tire Sections"],
21
+ "Step 7": ["Delay in sidewall stitching", "Lack of raw material"],
22
+ "Step 8": ["No person available to load Carcass", "No person available to collect tire"]
23
+ }
24
+
25
+ def get_step_info(step_number):
26
+ """Returns detailed information about a manufacturing step."""
27
+ step_details = {
28
+ 1: {
29
+ "Name": "Bead Insertion",
30
+ "Standard Time": "4 seconds",
31
+ "Video_substeps_expected": {
32
+ "0-1 second": "Machine starts bead insertion process.",
33
+ "1-3 seconds": "Beads are aligned and positioned.",
34
+ "3-4 seconds": "Final adjustment and confirmation of bead placement."
35
+ },
36
+ "Potential_Delay_Reasons": [
37
+ "Delay in bead insertion",
38
+ "Lack of raw material",
39
+ "Machine malfunction during bead alignment"
40
+ ]
41
+ },
42
+ 2: {
43
+ "Name": "Inner Liner Apply",
44
+ "Standard Time": "4 seconds",
45
+ "Video_substeps_expected": {
46
+ "0-1 second": "Machine applies the first layer of the liner.",
47
+ "1-3 seconds": "Technician checks alignment and adjusts if needed.",
48
+ "3-4 seconds": "Final inspection and confirmation."
49
+ },
50
+ "Potential_Delay_Reasons": [
51
+ "Technician adjusting inner liner alignment",
52
+ "Person rebuilding defective tire sections",
53
+ "Machine alignment issues"
54
+ ]
55
+ },
56
+ 3: {
57
+ "Name": "Ply1 Apply",
58
+ "Standard Time": "4 seconds",
59
+ "Video_substeps_expected": {
60
+ "0-2 seconds": "First ply is loaded onto the machine.",
61
+ "2-4 seconds": "Technician inspects and adjusts ply placement."
62
+ },
63
+ "Potential_Delay_Reasons": [
64
+ "Manual adjustment of ply placement",
65
+ "Technician repairing defective ply sections",
66
+ "Ply loading issues"
67
+ ]
68
+ },
69
+ 4: {
70
+ "Name": "Bead Set",
71
+ "Standard Time": "8 seconds",
72
+ "Video_substeps_expected": {
73
+ "0-3 seconds": "Bead is positioned and pre-set.",
74
+ "3-6 seconds": "Machine secures the bead in place.",
75
+ "6-8 seconds": "Technician confirms the bead alignment."
76
+ },
77
+ "Potential_Delay_Reasons": [
78
+ "Delay in bead positioning",
79
+ "Lack of raw material",
80
+ "Machine securing process failure"
81
+ ]
82
+ },
83
+ 5: {
84
+ "Name": "Turnup",
85
+ "Standard Time": "4 seconds",
86
+ "Video_substeps_expected": {
87
+ "0-2 seconds": "Turnup process begins with machine handling.",
88
+ "2-4 seconds": "Technician inspects the turnup and makes adjustments if necessary."
89
+ },
90
+ "Potential_Delay_Reasons": [
91
+ "Delay in turnup handling",
92
+ "Lack of raw material",
93
+ "Technician adjustment delays"
94
+ ]
95
+ },
96
+ 6: {
97
+ "Name": "Sidewall Apply",
98
+ "Standard Time": "14 seconds",
99
+ "Video_substeps_expected": {
100
+ "0-5 seconds": "Sidewall material is positioned by the machine.",
101
+ "5-10 seconds": "Technician checks for alignment and begins application.",
102
+ "10-14 seconds": "Final adjustments and confirmation of sidewall placement."
103
+ },
104
+ "Potential_Delay_Reasons": [
105
+ "Person repairing sidewall",
106
+ "Person rebuilding defective tire sections",
107
+ "Sidewall positioning issues"
108
+ ]
109
+ },
110
+ 7: {
111
+ "Name": "Sidewall Stitching",
112
+ "Standard Time": "5 seconds",
113
+ "Video_substeps_expected": {
114
+ "0-2 seconds": "Stitching process begins automatically.",
115
+ "2-4 seconds": "Technician inspects stitching for any irregularities.",
116
+ "4-5 seconds": "Machine completes stitching process."
117
+ },
118
+ "Potential_Delay_Reasons": [
119
+ "Delay in stitching process",
120
+ "Technician repairing stitching irregularities",
121
+ "Machine stitching malfunction"
122
+ ]
123
+ },
124
+ 8: {
125
+ "Name": "Carcass Unload",
126
+ "Standard Time": "7 seconds",
127
+ "Video_substeps_expected": {
128
+ "0-3 seconds": "Technician unloads(removes) carcass(tire) from the machine."
129
+ },
130
+ "Potential_Delay_reasons": [
131
+ "Person not available in time(in 3 sec) to remove carcass.",
132
+ "Person is doing bead(ring) insertion before carcass unload causing unload to be delayed by more than 3 sec"
133
+ ]
134
+ }
135
+ }
136
+
137
+ return step_details.get(step_number, {"Error": "Invalid step number. Please provide a valid step number."})
138
+
139
+
140
+
141
+ def load_video(video_data, strategy='chat'):
142
+ """Loads and processes video data into a format suitable for model input."""
143
+ bridge.set_bridge('torch')
144
+ num_frames = 24
145
+
146
+ if isinstance(video_data, str):
147
+ decord_vr = VideoReader(video_data, ctx=cpu(0))
148
+ else:
149
+ decord_vr = VideoReader(io.BytesIO(video_data), ctx=cpu(0))
150
+
151
+ frame_id_list = []
152
+ total_frames = len(decord_vr)
153
+ timestamps = [i[0] for i in decord_vr.get_frame_timestamp(np.arange(total_frames))]
154
+ max_second = round(max(timestamps)) + 1
155
+
156
+ for second in range(max_second):
157
+ closest_num = min(timestamps, key=lambda x: abs(x - second))
158
+ index = timestamps.index(closest_num)
159
+ frame_id_list.append(index)
160
+ if len(frame_id_list) >= num_frames:
161
+ break
162
+
163
+ video_data = decord_vr.get_batch(frame_id_list)
164
+ video_data = video_data.permute(3, 0, 1, 2)
165
+ return video_data
166
+
167
  def load_model():
168
+ """Loads the pre-trained model and tokenizer with quantization configurations."""
169
  quantization_config = BitsAndBytesConfig(
170
  load_in_4bit=True,
171
  bnb_4bit_compute_dtype=TORCH_TYPE,
 
181
  quantization_config=quantization_config,
182
  device_map="auto"
183
  ).eval()
184
+
185
  return model, tokenizer
186
 
187
+ def predict(prompt, video_data, temperature, model, tokenizer):
188
+ """Generates predictions based on the video and textual prompt."""
189
+ video = load_video(video_data, strategy='chat')
190
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  inputs = model.build_conversation_input_ids(
192
  tokenizer=tokenizer,
193
  query=prompt,
194
+ images=[video],
195
  history=[],
196
  template_version='chat'
197
  )
 
200
  'input_ids': inputs['input_ids'].unsqueeze(0).to(DEVICE),
201
  'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to(DEVICE),
202
  'attention_mask': inputs['attention_mask'].unsqueeze(0).to(DEVICE),
203
+ 'images': [[inputs['images'][0].to(DEVICE).to(TORCH_TYPE)]],
204
  }
205
 
206
  gen_kwargs = {
207
+ "max_new_tokens": 2048,
208
  "pad_token_id": 128002,
209
  "top_k": 1,
210
  "do_sample": False,
 
214
 
215
  with torch.no_grad():
216
  outputs = model.generate(**inputs, **gen_kwargs)
217
+ outputs = outputs[:, inputs['input_ids'].shape[1]:]
218
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
219
+
220
  return response
221
 
222
+ def get_analysis_prompt(step_number):
223
+ """Constructs the prompt for analyzing delay reasons based on the selected step."""
224
+ step_info = get_step_info(step_number)
225
+
226
+ if "Error" in step_info:
227
+ return step_info["Error"]
228
+
229
+ step_name = step_info["Name"]
230
+ standard_time = step_info["Standard Time"]
231
+ analysis = step_info["Analysis"]
232
+
233
+ return f"""
234
+ You are an AI expert system specialized in analyzing manufacturing processes and identifying production delays in tire manufacturing. Your role is to accurately classify delay reasons based on visual evidence from production line footage.
235
+ Task Context:
236
+ You are analyzing video footage from Step {step_number} of a tire manufacturing process where a delay has been detected. The step is called {step_name}, and its standard time is {standard_time}.
237
+ Required Analysis:
238
+ Carefully observe the video for visual cues indicating production interruption.
239
+ - If no person is visible in any of the frames, the reason probably might be due to their absence.
240
+ - If a person is visible in the video and is observed touching and modifying the layers of the tire, it indicates an issue with tire patching, and the person might be repairing it.
241
+ - Compare observed evidence against the following possible delay reasons:
242
+ - {analysis}
243
+ Following are the subactivities needs to happen in this step.
244
+
245
+ {get_step_info(step_number)}
246
+
247
+ Please provide your output in the following format:
248
+ Output_Examples = {
249
+ ["Delay in Bead Insertion", "Lack of raw material"],
250
+ ["Inner Liner Adjustment by Technician", "Person rebuilding defective Tire Sections"],
251
+ ["Manual Adjustment in Ply1 Apply", "Technician repairing defective Tire Sections"],
252
+ ["Delay in Bead Set", "Lack of raw material"],
253
+ ["Delay in Turnup", "Lack of raw material"],
254
+ ["Person Repairing Sidewall", "Person rebuilding defective Tire Sections"],
255
+ ["Delay in Sidewall Stitching", "Lack of raw material"],
256
+ ["No person available to load Carcass", "No person available to collect tire"]
257
+ }
258
+ 1. **Selected Reason:** [State the most likely reason from the given options]
259
+ 2. **Visual Evidence:** [Describe specific visual cues that support your selection]
260
+ 3. **Reasoning:** [Explain why this reason best matches the observed evidence]
261
+ 4. **Alternative Analysis:** [Brief explanation of why other possible reasons are less likely]
262
+ Important: Base your analysis solely on visual evidence from the video. Focus on concrete, observable details rather than assumptions. Clearly state if no person or specific activity is observed.
263
+ """
264
+
265
+
266
+
267
+ model, tokenizer = load_model()
268
+
269
+ def inference(video, step_number):
270
+ """Analyzes video to predict possible issues based on the manufacturing step."""
271
  try:
272
+ if not video:
273
+ return "Please upload a video first."
274
 
 
275
  prompt = get_analysis_prompt(step_number)
276
+ temperature = 0.3
277
+ response = predict(prompt, video, temperature, model, tokenizer)
278
+
279
  return response
280
  except Exception as e:
281
  return f"An error occurred during analysis: {str(e)}"
282
 
 
283
  def create_interface():
284
+ """Creates the Gradio interface for the Manufacturing Analysis System."""
285
  with gr.Blocks() as demo:
286
  gr.Markdown("""
287
+ # Manufacturing Analysis System
288
+ Upload a video of the manufacturing step and select the step number.
289
+ The system will analyze the video and provide observations.
290
  """)
291
 
292
  with gr.Row():
293
  with gr.Column():
294
+ video = gr.Video(label="Upload Manufacturing Video", sources=["upload"])
295
  step_number = gr.Dropdown(
296
  choices=[f"Step {i}" for i in range(1, 9)],
297
  label="Manufacturing Step"
 
301
  with gr.Column():
302
  output = gr.Textbox(label="Analysis Result", lines=10)
303
 
304
+ gr.Examples(
305
+ examples=[
306
+ ["7838_step2_2_eval.mp4", "Step 2"],
307
+ ["7838_step6_2_eval.mp4", "Step 6"],
308
+ ["7838_step8_1_eval.mp4", "Step 8"],
309
+ ["7993_step6_3_eval.mp4", "Step 6"],
310
+ ["7993_step8_3_eval.mp4", "Step 8"]
311
+ ],
312
+ inputs=[video, step_number],
313
+ cache_examples=False
314
+ )
315
+
316
  analyze_btn.click(
317
  fn=inference,
318
+ inputs=[video, step_number],
319
  outputs=[output]
320
  )
321
+
322
  return demo
323
 
324
  if __name__ == "__main__":
325
  demo = create_interface()
326
+ demo.queue().launch(share=True)