Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,62 +1,29 @@
|
|
| 1 |
-
# app.py - Hugging Face Spaces App
|
| 2 |
-
import gradio as gr
|
| 3 |
import torch
|
| 4 |
-
import
|
| 5 |
import numpy as np
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
-
from transformers import
|
| 8 |
-
|
| 9 |
-
import tempfile
|
| 10 |
-
import os
|
| 11 |
-
|
| 12 |
-
# Model configuration
|
| 13 |
-
MODEL_ID = "llava-hf/llava-v1.6-mistral-7b-hf"
|
| 14 |
-
PEFT_MODEL_ID = "arjunanand13/gas_pipe_llava_finetunedv2"
|
| 15 |
|
| 16 |
-
|
| 17 |
-
def load_model():
|
| 18 |
-
"""Load the fine-tuned PEFT model"""
|
| 19 |
-
print("Loading PEFT model...")
|
| 20 |
-
|
| 21 |
-
# Quantization config
|
| 22 |
-
bnb_config = BitsAndBytesConfig(
|
| 23 |
-
load_in_4bit=True,
|
| 24 |
-
bnb_4bit_quant_type="nf4",
|
| 25 |
-
bnb_4bit_compute_dtype=torch.float16,
|
| 26 |
-
bnb_4bit_use_double_quant=True,
|
| 27 |
-
bnb_4bit_quant_storage=torch.uint8
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
# Load processor
|
| 31 |
-
processor = AutoProcessor.from_pretrained(PEFT_MODEL_ID)
|
| 32 |
-
|
| 33 |
-
# Load base model
|
| 34 |
-
base_model = LlavaNextForConditionalGeneration.from_pretrained(
|
| 35 |
-
MODEL_ID,
|
| 36 |
-
torch_dtype=torch.float16,
|
| 37 |
-
quantization_config=bnb_config,
|
| 38 |
-
device_map="auto",
|
| 39 |
-
low_cpu_mem_usage=True,
|
| 40 |
-
trust_remote_code=True
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
# Load PEFT adapters
|
| 44 |
-
model = PeftModel.from_pretrained(base_model, PEFT_MODEL_ID)
|
| 45 |
-
|
| 46 |
-
print("Model loaded successfully!")
|
| 47 |
-
return processor, model
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
"""Extract 4 frames and create 2x2 grid"""
|
| 54 |
cap = cv2.VideoCapture(video_path)
|
| 55 |
if not cap.isOpened():
|
| 56 |
raise ValueError(f"Cannot open video: {video_path}")
|
| 57 |
|
| 58 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
frames = []
|
| 62 |
for frame_idx in frame_indices:
|
|
@@ -64,8 +31,10 @@ def preprocess_video(video_path):
|
|
| 64 |
ret, frame = cap.read()
|
| 65 |
if ret:
|
| 66 |
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 67 |
-
frame_pil = Image.fromarray(frame_rgb)
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
cap.release()
|
| 70 |
|
| 71 |
while len(frames) < 4:
|
|
@@ -74,124 +43,118 @@ def preprocess_video(video_path):
|
|
| 74 |
else:
|
| 75 |
frames.append(Image.new('RGB', (112, 112), color='black'))
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
return grid_image
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
try:
|
| 90 |
-
|
| 91 |
-
grid_image =
|
| 92 |
|
| 93 |
-
|
| 94 |
-
prompt = "[INST] <image>\nGas pipe test result? [/INST] {\"cheating\":"
|
| 95 |
-
inputs = processor(text=prompt, images=grid_image, return_tensors="pt")
|
| 96 |
|
| 97 |
-
|
| 98 |
-
inputs = {k: v.to(model.device) if hasattr(v, 'to') else v for k, v in inputs.items()}
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
**inputs,
|
| 103 |
-
max_new_tokens=16,
|
| 104 |
-
do_sample=False,
|
| 105 |
-
pad_token_id=processor.tokenizer.eos_token_id
|
| 106 |
-
)
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
| 115 |
-
prediction = "CHEATING DETECTED"
|
| 116 |
-
explanation = "The system detected violations in the testing procedure."
|
| 117 |
-
status = "🚨"
|
| 118 |
-
else:
|
| 119 |
-
prediction = "COMPLIANT PROCEDURE"
|
| 120 |
-
explanation = "The testing procedure appears to follow proper protocols."
|
| 121 |
-
status = "✅"
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
return formatted_result, grid_image
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
-
|
| 131 |
-
with gr.Blocks(
|
| 132 |
-
|
| 133 |
-
theme=gr.themes.Soft(),
|
| 134 |
-
css="""
|
| 135 |
-
.gradio-container {
|
| 136 |
-
max-width: 1200px;
|
| 137 |
-
margin: auto;
|
| 138 |
-
}
|
| 139 |
-
"""
|
| 140 |
-
) as demo:
|
| 141 |
-
|
| 142 |
-
gr.HTML("""
|
| 143 |
-
<div style="text-align: center; margin-bottom: 20px;">
|
| 144 |
-
<h1>🔧 Gas Pipe Quality Control Detection</h1>
|
| 145 |
-
<p>AI-powered detection of compliance violations in gas pipe testing procedures</p>
|
| 146 |
-
</div>
|
| 147 |
-
""")
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
with gr.Row():
|
| 152 |
-
with gr.Column(scale=2):
|
| 153 |
-
video_input = gr.Video(
|
| 154 |
-
label="Upload Gas Pipe Testing Video",
|
| 155 |
-
height=320
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
analyze_btn = gr.Button(
|
| 159 |
-
"Analyze Video",
|
| 160 |
-
variant="primary",
|
| 161 |
-
size="lg"
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
gr.Markdown("""
|
| 165 |
-
**Supported formats:** MP4, AVI, MOV, WMV
|
| 166 |
-
**Max duration:** 60 seconds recommended
|
| 167 |
-
""")
|
| 168 |
|
| 169 |
-
with gr.
|
| 170 |
-
|
| 171 |
-
label="
|
| 172 |
-
|
| 173 |
-
max_lines=12
|
| 174 |
-
)
|
| 175 |
|
| 176 |
-
|
| 177 |
-
label="
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
|
| 189 |
-
<div style="text-align: center; margin-top: 20px; padding: 20px; background-color: #f8f9fa; border-radius: 10px;">
|
| 190 |
-
<p><strong>Model:</strong> Fine-tuned LLaVA v1.6 Mistral 7B with LoRA adapters</p>
|
| 191 |
-
<p><strong>Repository:</strong> <a href="https://huggingface.co/arjunanand13/gas_pipe_llava_finetunedv2" target="_blank">arjunanand13/gas_pipe_llava_finetunedv2</a></p>
|
| 192 |
-
<p><strong>Developed by:</strong> Arjun Anand</p>
|
| 193 |
-
</div>
|
| 194 |
-
""")
|
| 195 |
|
| 196 |
if __name__ == "__main__":
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import gradio as gr
|
| 3 |
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
from PIL import Image
|
| 6 |
+
from transformers import BitsAndBytesConfig, LlavaNextForConditionalGeneration, AutoProcessor
|
| 7 |
+
import gc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
MODEL_ID = "arjunanand13/gas_pipe_llava_finetunedv3"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
def clear_memory():
|
| 12 |
+
gc.collect()
|
| 13 |
+
if torch.cuda.is_available():
|
| 14 |
+
torch.cuda.empty_cache()
|
| 15 |
+
torch.cuda.synchronize()
|
| 16 |
|
| 17 |
+
def extract_frames_from_video(video_path, num_frames=4):
|
|
|
|
| 18 |
cap = cv2.VideoCapture(video_path)
|
| 19 |
if not cap.isOpened():
|
| 20 |
raise ValueError(f"Cannot open video: {video_path}")
|
| 21 |
|
| 22 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 23 |
+
if total_frames < num_frames:
|
| 24 |
+
num_frames = min(total_frames, num_frames)
|
| 25 |
+
|
| 26 |
+
frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
|
| 27 |
|
| 28 |
frames = []
|
| 29 |
for frame_idx in frame_indices:
|
|
|
|
| 31 |
ret, frame = cap.read()
|
| 32 |
if ret:
|
| 33 |
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 34 |
+
frame_pil = Image.fromarray(frame_rgb)
|
| 35 |
+
frame_resized = frame_pil.resize((112, 112), Image.Resampling.LANCZOS)
|
| 36 |
+
frames.append(frame_resized)
|
| 37 |
+
|
| 38 |
cap.release()
|
| 39 |
|
| 40 |
while len(frames) < 4:
|
|
|
|
| 43 |
else:
|
| 44 |
frames.append(Image.new('RGB', (112, 112), color='black'))
|
| 45 |
|
| 46 |
+
return frames[:4]
|
| 47 |
+
|
| 48 |
+
def create_frame_grid(frames, grid_size=(2, 2)):
|
| 49 |
+
cols, rows = grid_size
|
| 50 |
+
frame_size = 112
|
| 51 |
+
grid_width = frame_size * cols
|
| 52 |
+
grid_height = frame_size * rows
|
| 53 |
+
|
| 54 |
+
grid_image = Image.new('RGB', (grid_width, grid_height))
|
| 55 |
+
|
| 56 |
+
for i, frame in enumerate(frames):
|
| 57 |
+
row = i // cols
|
| 58 |
+
col = i % cols
|
| 59 |
+
x = col * frame_size
|
| 60 |
+
y = row * frame_size
|
| 61 |
+
grid_image.paste(frame, (x, y))
|
| 62 |
|
| 63 |
return grid_image
|
| 64 |
|
| 65 |
+
@torch.no_grad()
|
| 66 |
+
def load_model():
|
| 67 |
+
bnb_config = BitsAndBytesConfig(
|
| 68 |
+
load_in_4bit=True,
|
| 69 |
+
bnb_4bit_quant_type="nf4",
|
| 70 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 71 |
+
bnb_4bit_use_double_quant=True,
|
| 72 |
+
bnb_4bit_quant_storage=torch.uint8
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 76 |
+
processor.tokenizer.padding_side = "right"
|
| 77 |
+
processor.tokenizer.pad_token = processor.tokenizer.eos_token
|
| 78 |
|
| 79 |
+
model = LlavaNextForConditionalGeneration.from_pretrained(
|
| 80 |
+
MODEL_ID,
|
| 81 |
+
torch_dtype=torch.float16,
|
| 82 |
+
quantization_config=bnb_config,
|
| 83 |
+
device_map="auto",
|
| 84 |
+
low_cpu_mem_usage=True,
|
| 85 |
+
trust_remote_code=True
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
model.config.use_cache = False
|
| 89 |
+
model.eval()
|
| 90 |
+
|
| 91 |
+
return model, processor
|
| 92 |
+
|
| 93 |
+
model, processor = load_model()
|
| 94 |
+
|
| 95 |
+
def predict_gas_pipe_quality(video_path):
|
| 96 |
try:
|
| 97 |
+
frames = extract_frames_from_video(video_path, num_frames=4)
|
| 98 |
+
grid_image = create_frame_grid(frames, grid_size=(2, 2))
|
| 99 |
|
| 100 |
+
prompt = "[INST] <image>\nGas pipe test result? [/INST]"
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
inputs = processor(text=prompt, images=grid_image, return_tensors="pt")
|
|
|
|
| 103 |
|
| 104 |
+
if torch.cuda.is_available():
|
| 105 |
+
inputs = {k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
with torch.no_grad():
|
| 108 |
+
generated_ids = model.generate(
|
| 109 |
+
input_ids=inputs["input_ids"],
|
| 110 |
+
attention_mask=inputs["attention_mask"],
|
| 111 |
+
pixel_values=inputs["pixel_values"],
|
| 112 |
+
image_sizes=inputs["image_sizes"],
|
| 113 |
+
max_new_tokens=16,
|
| 114 |
+
do_sample=False,
|
| 115 |
+
pad_token_id=processor.tokenizer.eos_token_id
|
| 116 |
+
)
|
| 117 |
|
| 118 |
+
prediction = processor.batch_decode(
|
| 119 |
+
generated_ids[:, inputs["input_ids"].size(1):],
|
| 120 |
+
skip_special_tokens=True
|
| 121 |
+
)[0].strip()
|
| 122 |
|
| 123 |
+
clear_memory()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
return grid_image, prediction
|
|
|
|
|
|
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
+
clear_memory()
|
| 129 |
+
return None, f"Error: {str(e)}"
|
| 130 |
|
| 131 |
+
def create_interface():
|
| 132 |
+
with gr.Blocks(title="Gas Pipe Quality Control") as iface:
|
| 133 |
+
gr.Markdown("# Gas Pipe Quality Control")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
with gr.Row():
|
| 136 |
+
with gr.Column():
|
| 137 |
+
video_input = gr.Video(label="Upload Video")
|
| 138 |
+
analyze_btn = gr.Button("Analyze", variant="primary")
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
with gr.Column():
|
| 141 |
+
frame_grid = gr.Image(label="Extracted Frames")
|
| 142 |
+
result_output = gr.Textbox(label="Model Output", lines=3)
|
| 143 |
+
|
| 144 |
+
analyze_btn.click(
|
| 145 |
+
fn=predict_gas_pipe_quality,
|
| 146 |
+
inputs=video_input,
|
| 147 |
+
outputs=[frame_grid, result_output]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
video_input.change(
|
| 151 |
+
fn=predict_gas_pipe_quality,
|
| 152 |
+
inputs=video_input,
|
| 153 |
+
outputs=[frame_grid, result_output]
|
| 154 |
+
)
|
| 155 |
|
| 156 |
+
return iface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
if __name__ == "__main__":
|
| 159 |
+
iface = create_interface()
|
| 160 |
+
iface.launch(share=True)
|