VishalD1234 commited on
Commit
33101ab
·
verified ·
1 Parent(s): 495550d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -240
app.py CHANGED
@@ -1,169 +1,13 @@
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(
@@ -184,14 +28,15 @@ def load_model():
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
  )
@@ -204,7 +49,7 @@ def predict(prompt, video_data, temperature, model, tokenizer):
204
  }
205
 
206
  gen_kwargs = {
207
- "max_new_tokens": 2048,
208
  "pad_token_id": 128002,
209
  "top_k": 1,
210
  "do_sample": False,
@@ -219,103 +64,41 @@ def predict(prompt, video_data, temperature, model, tokenizer):
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"
298
- )
299
- analyze_btn = gr.Button("Analyze", variant="primary")
300
 
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
 
@@ -323,4 +106,4 @@ def create_interface():
323
 
324
  if __name__ == "__main__":
325
  demo = create_interface()
326
- demo.queue().launch(share=True)
 
1
  import gradio as gr
 
 
2
  import torch
3
+ import numpy as np
4
+ from PIL import Image
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
6
 
7
  MODEL_PATH = "THUDM/cogvlm2-llama3-caption"
8
  DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
9
  TORCH_TYPE = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else torch.float16
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def load_model():
12
  """Loads the pre-trained model and tokenizer with quantization configurations."""
13
  quantization_config = BitsAndBytesConfig(
 
28
 
29
  return model, tokenizer
30
 
31
+ def predict_image(prompt, image, temperature, model, tokenizer):
32
+ """Generates predictions based on the image and textual prompt."""
33
+ image = image.convert("RGB") # Ensure image is in RGB format
34
 
35
+ # Convert image to model-expected format
36
  inputs = model.build_conversation_input_ids(
37
  tokenizer=tokenizer,
38
  query=prompt,
39
+ images=[image],
40
  history=[],
41
  template_version='chat'
42
  )
 
49
  }
50
 
51
  gen_kwargs = {
52
+ "max_new_tokens": 512,
53
  "pad_token_id": 128002,
54
  "top_k": 1,
55
  "do_sample": False,
 
64
 
65
  return response
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  model, tokenizer = load_model()
68
 
69
+ def inference(image):
70
+ """Generates a description of the input image."""
71
  try:
72
+ if not image:
73
+ return "Please upload an image first."
74
 
75
+ prompt = "Describe the image and the components observed in the given input image."
76
  temperature = 0.3
77
+ response = predict_image(prompt, image, temperature, model, tokenizer)
78
 
79
  return response
80
  except Exception as e:
81
  return f"An error occurred during analysis: {str(e)}"
82
 
83
  def create_interface():
84
+ """Creates the Gradio interface for Image Description System."""
85
  with gr.Blocks() as demo:
86
  gr.Markdown("""
87
+ # Image Description System
88
+ Upload an image, and the system will describe the image and its components.
 
89
  """)
90
 
91
  with gr.Row():
92
  with gr.Column():
93
+ image_input = gr.Image(label="Upload Image", type="pil")
94
+ analyze_btn = gr.Button("Describe Image", variant="primary")
 
 
 
 
95
 
96
  with gr.Column():
97
+ output = gr.Textbox(label="Image Description", lines=10)
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  analyze_btn.click(
100
  fn=inference,
101
+ inputs=[image_input],
102
  outputs=[output]
103
  )
104
 
 
106
 
107
  if __name__ == "__main__":
108
  demo = create_interface()
109
+ demo.queue().launch(share=True)