Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -6,7 +6,7 @@ from decord import cpu, VideoReader, bridge
|
|
6 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
from transformers import BitsAndBytesConfig
|
8 |
|
9 |
-
MODEL_PATH = "THUDM/cogvlm2-
|
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 |
|
@@ -22,8 +22,91 @@ DELAY_REASONS = {
|
|
22 |
"Step 8": ["No person available to load Carcass", "No person available to collect tire"]
|
23 |
}
|
24 |
|
25 |
-
def
|
26 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
step_details = {
|
28 |
1: {
|
29 |
"Name": "Bead Insertion",
|
@@ -127,101 +210,14 @@ def get_step_info(step_number):
|
|
127 |
"Video_substeps_expected": {
|
128 |
"0-3 seconds": "Technician unloads(removes) carcass(tire) from the machine."
|
129 |
},
|
130 |
-
"
|
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 |
-
|
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,
|
172 |
-
bnb_4bit_use_double_quant=True,
|
173 |
-
bnb_4bit_quant_type="nf4"
|
174 |
-
)
|
175 |
-
|
176 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
177 |
-
model = AutoModelForCausalLM.from_pretrained(
|
178 |
-
MODEL_PATH,
|
179 |
-
torch_dtype=TORCH_TYPE,
|
180 |
-
trust_remote_code=True,
|
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 |
-
)
|
198 |
-
|
199 |
-
inputs = {
|
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,
|
211 |
-
"top_p": 0.1,
|
212 |
-
"temperature": temperature,
|
213 |
-
}
|
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"]
|
@@ -230,45 +226,53 @@ def get_analysis_prompt(step_number):
|
|
230 |
standard_time = step_info["Standard Time"]
|
231 |
video_substeps = step_info["Video_substeps_expected"]
|
232 |
potential_delay_reasons = step_info["Potential_Delay_Reasons"]
|
233 |
-
|
234 |
-
# Format substeps for the prompt
|
235 |
-
substeps_text = "\n".join([f" {time}: {description}" for time, description in video_substeps.items()])
|
236 |
-
|
237 |
-
# Format potential delay reasons
|
238 |
-
potential_reasons_text = "\n - ".join(potential_delay_reasons)
|
239 |
-
|
240 |
return f"""
|
241 |
-
You are an AI expert system specialized in analyzing manufacturing processes and identifying production delays in tire manufacturing. Your
|
|
|
|
|
|
|
242 |
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
- **Standard Time**: {standard_time}
|
247 |
|
248 |
-
|
249 |
-
{
|
|
|
|
|
|
|
250 |
|
251 |
-
|
252 |
-
|
253 |
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
|
260 |
-
|
261 |
-
|
|
|
|
|
|
|
262 |
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
|
|
|
|
|
|
|
|
|
|
268 |
"""
|
269 |
|
270 |
|
271 |
|
|
|
272 |
model, tokenizer = load_model()
|
273 |
|
274 |
def inference(video, step_number):
|
|
|
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 |
|
|
|
22 |
"Step 8": ["No person available to load Carcass", "No person available to collect tire"]
|
23 |
}
|
24 |
|
25 |
+
def load_video(video_data, strategy='chat'):
|
26 |
+
"""Loads and processes video data into a format suitable for model input."""
|
27 |
+
bridge.set_bridge('torch')
|
28 |
+
num_frames = 24
|
29 |
+
|
30 |
+
if isinstance(video_data, str):
|
31 |
+
decord_vr = VideoReader(video_data, ctx=cpu(0))
|
32 |
+
else:
|
33 |
+
decord_vr = VideoReader(io.BytesIO(video_data), ctx=cpu(0))
|
34 |
+
|
35 |
+
frame_id_list = []
|
36 |
+
total_frames = len(decord_vr)
|
37 |
+
timestamps = [i[0] for i in decord_vr.get_frame_timestamp(np.arange(total_frames))]
|
38 |
+
max_second = round(max(timestamps)) + 1
|
39 |
+
|
40 |
+
for second in range(max_second):
|
41 |
+
closest_num = min(timestamps, key=lambda x: abs(x - second))
|
42 |
+
index = timestamps.index(closest_num)
|
43 |
+
frame_id_list.append(index)
|
44 |
+
if len(frame_id_list) >= num_frames:
|
45 |
+
break
|
46 |
+
|
47 |
+
video_data = decord_vr.get_batch(frame_id_list)
|
48 |
+
video_data = video_data.permute(3, 0, 1, 2)
|
49 |
+
return video_data
|
50 |
+
|
51 |
+
def load_model():
|
52 |
+
"""Loads the pre-trained model and tokenizer with quantization configurations."""
|
53 |
+
quantization_config = BitsAndBytesConfig(
|
54 |
+
load_in_4bit=True,
|
55 |
+
bnb_4bit_compute_dtype=TORCH_TYPE,
|
56 |
+
bnb_4bit_use_double_quant=True,
|
57 |
+
bnb_4bit_quant_type="nf4"
|
58 |
+
)
|
59 |
+
|
60 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
61 |
+
model = AutoModelForCausalLM.from_pretrained(
|
62 |
+
MODEL_PATH,
|
63 |
+
torch_dtype=TORCH_TYPE,
|
64 |
+
trust_remote_code=True,
|
65 |
+
quantization_config=quantization_config,
|
66 |
+
device_map="auto"
|
67 |
+
).eval()
|
68 |
+
|
69 |
+
return model, tokenizer
|
70 |
+
|
71 |
+
def predict(prompt, video_data, temperature, model, tokenizer):
|
72 |
+
"""Generates predictions based on the video and textual prompt."""
|
73 |
+
video = load_video(video_data, strategy='chat')
|
74 |
+
|
75 |
+
inputs = model.build_conversation_input_ids(
|
76 |
+
tokenizer=tokenizer,
|
77 |
+
query=prompt,
|
78 |
+
images=[video],
|
79 |
+
history=[],
|
80 |
+
template_version='chat'
|
81 |
+
)
|
82 |
+
|
83 |
+
inputs = {
|
84 |
+
'input_ids': inputs['input_ids'].unsqueeze(0).to(DEVICE),
|
85 |
+
'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to(DEVICE),
|
86 |
+
'attention_mask': inputs['attention_mask'].unsqueeze(0).to(DEVICE),
|
87 |
+
'images': [[inputs['images'][0].to(DEVICE).to(TORCH_TYPE)]],
|
88 |
+
}
|
89 |
+
|
90 |
+
gen_kwargs = {
|
91 |
+
"max_new_tokens": 2048,
|
92 |
+
"pad_token_id": 128002,
|
93 |
+
"top_k": 1,
|
94 |
+
"do_sample": False,
|
95 |
+
"top_p": 0.1,
|
96 |
+
"temperature": temperature,
|
97 |
+
}
|
98 |
+
|
99 |
+
with torch.no_grad():
|
100 |
+
outputs = model.generate(**inputs, **gen_kwargs)
|
101 |
+
outputs = outputs[:, inputs['input_ids'].shape[1]:]
|
102 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
103 |
+
|
104 |
+
return response
|
105 |
+
|
106 |
+
def get_analysis_prompt(step_number):
|
107 |
+
"""Constructs the prompt for analyzing delay reasons based on the selected step."""
|
108 |
+
|
109 |
+
# Step details dictionary included directly in the prompt
|
110 |
step_details = {
|
111 |
1: {
|
112 |
"Name": "Bead Insertion",
|
|
|
210 |
"Video_substeps_expected": {
|
211 |
"0-3 seconds": "Technician unloads(removes) carcass(tire) from the machine."
|
212 |
},
|
213 |
+
"Potential_Delay_Reasons": [
|
214 |
"Person not available in time(in 3 sec) to remove carcass.",
|
215 |
"Person is doing bead(ring) insertion before carcass unload causing unload to be delayed by more than 3 sec"
|
216 |
]
|
217 |
}
|
218 |
}
|
219 |
|
220 |
+
step_info = step_details.get(step_number, {"Error": "Invalid step number. Please provide a valid step number."})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
|
222 |
if "Error" in step_info:
|
223 |
return step_info["Error"]
|
|
|
226 |
standard_time = step_info["Standard Time"]
|
227 |
video_substeps = step_info["Video_substeps_expected"]
|
228 |
potential_delay_reasons = step_info["Potential_Delay_Reasons"]
|
229 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
230 |
return f"""
|
231 |
+
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.
|
232 |
+
Task Context:
|
233 |
+
The following are the details of all steps in the tire manufacturing process:
|
234 |
+
{step_details}
|
235 |
|
236 |
+
You are analyzing video footage from Step {step_number} of this process. 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 |
|
240 |
+
Step Details:
|
241 |
+
- **Name:** {step_name}
|
242 |
+
- **Standard Time:** {standard_time}
|
243 |
+
- **Video Substeps Expected:**
|
244 |
+
{video_substeps}
|
245 |
|
246 |
+
Possible Delay Reasons:
|
247 |
+
- {', '.join(potential_delay_reasons)}
|
248 |
|
249 |
+
Analysis Instructions:
|
250 |
+
1. Analyze the video frame by frame to identify evidence of delay or irregular activity.
|
251 |
+
2. If no person is visible in any of the frames, the reason might be the absence of required personnel.
|
252 |
+
3. If a person is visible and modifying tire components, it may indicate repair or alignment issues.
|
253 |
+
4. Match the observed evidence with the possible delay reasons listed above.
|
254 |
|
255 |
+
Output Format:
|
256 |
+
1. **Selected Reason:** [State the most likely reason from the list above]
|
257 |
+
2. **Visual Evidence:** [Describe specific visual cues that support your selection]
|
258 |
+
3. **Reasoning:** [Explain why this reason best matches the observed evidence]
|
259 |
+
4. **Alternative Analysis:** [Briefly explain why other potential reasons are less likely]
|
260 |
|
261 |
+
Important:
|
262 |
+
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 |
+
Example Output:
|
265 |
+
Output = {{
|
266 |
+
"Selected Reason": "Delay in bead insertion",
|
267 |
+
"Visual Evidence": "Technician is not present during the bead alignment process.",
|
268 |
+
"Reasoning": "The absence of the technician caused a delay in starting the bead insertion.",
|
269 |
+
"Alternative Analysis": "No raw material issues were visible, and the machine appeared functional."
|
270 |
+
}}
|
271 |
"""
|
272 |
|
273 |
|
274 |
|
275 |
+
|
276 |
model, tokenizer = load_model()
|
277 |
|
278 |
def inference(video, step_number):
|