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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import json
|
| 9 |
+
|
| 10 |
+
# Model Configuration
|
| 11 |
+
MODEL_PATH = "THUDM/cogvlm2-llama3-caption"
|
| 12 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 13 |
+
TORCH_TYPE = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else torch.float16
|
| 14 |
+
|
| 15 |
+
# Define delay reasons for each step
|
| 16 |
+
DELAY_REASONS = {
|
| 17 |
+
"Step 1": ["No raw material available", "Person repatching the tire"],
|
| 18 |
+
"Step 2": ["Person repatching the tire", "Lack of raw material"],
|
| 19 |
+
"Step 3": ["Person repatching the tire", "Lack of raw material"],
|
| 20 |
+
"Step 4": ["Person repatching the tire", "Lack of raw material"],
|
| 21 |
+
"Step 5": ["Person repatching the tire", "Lack of raw material"],
|
| 22 |
+
"Step 6": ["Person repatching the tire", "Lack of raw material"],
|
| 23 |
+
"Step 7": ["Person repatching the tire", "Lack of raw material"],
|
| 24 |
+
"Step 8": ["No person available to collect tire", "Person repatching the tire"]
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
def load_video(video_data, strategy='chat'):
|
| 28 |
+
bridge.set_bridge('torch')
|
| 29 |
+
mp4_stream = video_data
|
| 30 |
+
num_frames = 24
|
| 31 |
+
decord_vr = VideoReader(io.BytesIO(mp4_stream), ctx=cpu(0))
|
| 32 |
+
|
| 33 |
+
frame_id_list = []
|
| 34 |
+
total_frames = len(decord_vr)
|
| 35 |
+
timestamps = [i[0] for i in decord_vr.get_frame_timestamp(np.arange(total_frames))]
|
| 36 |
+
max_second = round(max(timestamps)) + 1
|
| 37 |
+
|
| 38 |
+
for second in range(max_second):
|
| 39 |
+
closest_num = min(timestamps, key=lambda x: abs(x - second))
|
| 40 |
+
index = timestamps.index(closest_num)
|
| 41 |
+
frame_id_list.append(index)
|
| 42 |
+
if len(frame_id_list) >= num_frames:
|
| 43 |
+
break
|
| 44 |
+
|
| 45 |
+
video_data = decord_vr.get_batch(frame_id_list)
|
| 46 |
+
video_data = video_data.permute(3, 0, 1, 2)
|
| 47 |
+
return video_data
|
| 48 |
+
|
| 49 |
+
def load_model():
|
| 50 |
+
quantization_config = BitsAndBytesConfig(
|
| 51 |
+
load_in_4bit=True,
|
| 52 |
+
bnb_4bit_compute_dtype=TORCH_TYPE,
|
| 53 |
+
bnb_4bit_use_double_quant=True,
|
| 54 |
+
bnb_4bit_quant_type="nf4"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
| 58 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 59 |
+
MODEL_PATH,
|
| 60 |
+
torch_dtype=TORCH_TYPE,
|
| 61 |
+
trust_remote_code=True,
|
| 62 |
+
quantization_config=quantization_config,
|
| 63 |
+
device_map="auto"
|
| 64 |
+
).eval()
|
| 65 |
+
|
| 66 |
+
return model, tokenizer
|
| 67 |
+
|
| 68 |
+
def predict(prompt, video_data, temperature, model, tokenizer):
|
| 69 |
+
video = load_video(video_data, strategy='chat')
|
| 70 |
+
|
| 71 |
+
inputs = model.build_conversation_input_ids(
|
| 72 |
+
tokenizer=tokenizer,
|
| 73 |
+
query=prompt,
|
| 74 |
+
images=[video],
|
| 75 |
+
history=[],
|
| 76 |
+
template_version='chat'
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
inputs = {
|
| 80 |
+
'input_ids': inputs['input_ids'].unsqueeze(0).to(DEVICE),
|
| 81 |
+
'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to(DEVICE),
|
| 82 |
+
'attention_mask': inputs['attention_mask'].unsqueeze(0).to(DEVICE),
|
| 83 |
+
'images': [[inputs['images'][0].to(DEVICE).to(TORCH_TYPE)]],
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
gen_kwargs = {
|
| 87 |
+
"max_new_tokens": 2048,
|
| 88 |
+
"pad_token_id": 128002,
|
| 89 |
+
"top_k": 1,
|
| 90 |
+
"do_sample": False,
|
| 91 |
+
"top_p": 0.1,
|
| 92 |
+
"temperature": temperature,
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
with torch.no_grad():
|
| 96 |
+
outputs = model.generate(**inputs, **gen_kwargs)
|
| 97 |
+
outputs = outputs[:, inputs['input_ids'].shape[1]:]
|
| 98 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 99 |
+
|
| 100 |
+
return response
|
| 101 |
+
|
| 102 |
+
def get_analysis_prompt(step_number, possible_reasons):
|
| 103 |
+
return f"""Analyze the video of Step {step_number} in the tire manufacturing process.
|
| 104 |
+
|
| 105 |
+
Possible delay reasons for this step are:
|
| 106 |
+
{', '.join(possible_reasons)}
|
| 107 |
+
|
| 108 |
+
Based on the video evidence, determine which of these reasons best explains the delay.
|
| 109 |
+
Please provide:
|
| 110 |
+
1. Your chosen reason from the list above
|
| 111 |
+
2. Specific visual evidence supporting this choice
|
| 112 |
+
3. Brief explanation of why other reasons are less likely
|
| 113 |
+
|
| 114 |
+
Focus your analysis on visual cues that support your conclusion."""
|
| 115 |
+
|
| 116 |
+
def inference(video, step_number, selected_reason):
|
| 117 |
+
if not video:
|
| 118 |
+
return "Please upload a video first."
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
model, tokenizer = load_model()
|
| 122 |
+
video_data = video.read()
|
| 123 |
+
|
| 124 |
+
# Get possible reasons for the selected step
|
| 125 |
+
possible_reasons = DELAY_REASONS[step_number]
|
| 126 |
+
|
| 127 |
+
# Generate the analysis prompt
|
| 128 |
+
prompt = get_analysis_prompt(step_number, possible_reasons)
|
| 129 |
+
|
| 130 |
+
# Get model prediction
|
| 131 |
+
temperature = 0.8
|
| 132 |
+
response = predict(prompt, video_data, temperature, model, tokenizer)
|
| 133 |
+
|
| 134 |
+
return response
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
return f"An error occurred: {str(e)}"
|
| 138 |
+
|
| 139 |
+
def update_reasons(step):
|
| 140 |
+
"""Update the dropdown choices based on the selected step"""
|
| 141 |
+
return gr.Dropdown(choices=DELAY_REASONS[step])
|
| 142 |
+
|
| 143 |
+
# Gradio Interface
|
| 144 |
+
def create_interface():
|
| 145 |
+
with gr.Blocks() as demo:
|
| 146 |
+
with gr.Row():
|
| 147 |
+
with gr.Column():
|
| 148 |
+
video = gr.Video(label="Upload Manufacturing Video", sources=["upload"])
|
| 149 |
+
step_number = gr.Dropdown(
|
| 150 |
+
choices=list(DELAY_REASONS.keys()),
|
| 151 |
+
label="Manufacturing Step",
|
| 152 |
+
value="Step 1"
|
| 153 |
+
)
|
| 154 |
+
reason = gr.Dropdown(
|
| 155 |
+
choices=DELAY_REASONS["Step 1"],
|
| 156 |
+
label="Select Delay Reason",
|
| 157 |
+
value=DELAY_REASONS["Step 1"][0]
|
| 158 |
+
)
|
| 159 |
+
analyze_btn = gr.Button("Analyze Delay", variant="primary")
|
| 160 |
+
|
| 161 |
+
with gr.Column():
|
| 162 |
+
output = gr.Textbox(label="Analysis Result", lines=10)
|
| 163 |
+
|
| 164 |
+
# Update reasons when step changes
|
| 165 |
+
step_number.change(
|
| 166 |
+
fn=update_reasons,
|
| 167 |
+
inputs=[step_number],
|
| 168 |
+
outputs=[reason]
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# Trigger analysis when button is clicked
|
| 172 |
+
analyze_btn.click(
|
| 173 |
+
fn=inference,
|
| 174 |
+
inputs=[video, step_number, reason],
|
| 175 |
+
outputs=[output]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
return demo
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
demo = create_interface()
|
| 182 |
+
demo.launch()
|