Spaces:
Sleeping
Sleeping
Download app.py from Madegwa/Accident_Severity_API: direct link, hf CLI and curl.
- Browser
- Download file 3.65 kB
-
https://huggingface.co/spaces/Madegwa/Accident_Severity_API/resolve/main/app.py
- Command line
-
hf download hf://spaces/Madegwa/Accident_Severity_API/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Madegwa/Accident_Severity_API/resolve/main/app.py
3.65 kB
| """ | |
| app.py (Hugging Face Gradio Space) | |
| Accident severity classifier. Weights are streamed from a Cloudflare R2 | |
| bucket into memory at startup (never written to disk, never exposed to | |
| callers). Frame extraction runs on CPU; only the model forward pass uses | |
| the ZeroGPU allocation, which keeps GPU time per request short. | |
| Space secrets required: | |
| R2_ENDPOINT, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY | |
| Optional: | |
| CHECKPOINT_KEY object name in the bucket (default accident_severity_model.pth) | |
| """ | |
| import io | |
| import os | |
| import boto3 | |
| import gradio as gr | |
| import torch | |
| import torch.nn as nn | |
| from botocore.config import Config | |
| from torchvision.models.video import r3d_18 | |
| # Same extraction code used in training/CLI inference, so preprocessing matches. | |
| from accident_severity_infer import extract_frames | |
| # ZeroGPU: the `spaces` package only exists on HF. Fall back to a no-op so | |
| # the same file also runs locally or on regular hardware. | |
| try: | |
| import spaces | |
| gpu = spaces.GPU(duration=30) | |
| except ImportError: | |
| def gpu(fn): | |
| return fn | |
| CHECKPOINT_KEY = os.getenv("CHECKPOINT_KEY", "accident_severity_model.pth") | |
| # ------------------------------------------------------------ | |
| # Model loading (once, at startup) | |
| # ------------------------------------------------------------ | |
| def load_checkpoint(): | |
| s3 = boto3.client( | |
| "s3", | |
| endpoint_url=os.environ["R2_ENDPOINT"], | |
| aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"], | |
| aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"], | |
| region_name="auto", | |
| config=Config(signature_version="s3v4"), | |
| ) | |
| obj = s3.get_object(Bucket=os.environ["R2_BUCKET"], Key=CHECKPOINT_KEY) | |
| buffer = io.BytesIO(obj["Body"].read()) # in memory only | |
| return torch.load(buffer, map_location="cpu") | |
| print(f"Loading '{CHECKPOINT_KEY}' from R2...") | |
| checkpoint = load_checkpoint() | |
| class_names = checkpoint["class_names"] | |
| model = r3d_18(weights=None) | |
| model.fc = nn.Linear(model.fc.in_features, len(class_names)) | |
| model.load_state_dict(checkpoint["state_dict"]) | |
| model.eval() | |
| print("Model ready.") | |
| # ------------------------------------------------------------ | |
| # Inference | |
| # ------------------------------------------------------------ | |
| def run_model(videos): | |
| """Forward pass only. This is the part that gets the GPU.""" | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| model.to(device) | |
| with torch.no_grad(): | |
| outputs = model(videos.to(device)) | |
| return torch.softmax(outputs, dim=1)[0].cpu().numpy() | |
| def predict(video_path): | |
| if not video_path: | |
| raise gr.Error("Please upload a video.") | |
| try: | |
| frames = extract_frames( | |
| video_path, | |
| num_frames=checkpoint["num_frames"], | |
| image_size=checkpoint["image_size"], | |
| window_seconds=checkpoint["motion_window_seconds"], | |
| stride=checkpoint.get("motion_sample_stride", 2), | |
| ) # (T, C, H, W) | |
| except (ValueError, RuntimeError) as e: | |
| raise gr.Error(f"Could not process video: {e}") | |
| videos = frames.unsqueeze(0).permute(0, 2, 1, 3, 4) # (1, C, T, H, W) | |
| probs = run_model(videos) | |
| return {c: float(p) for c, p in zip(class_names, probs)} | |
| demo = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Video(label="Crash clip (15-30s)"), | |
| outputs=gr.Label(num_top_classes=len(class_names), label="Predicted severity"), | |
| title="Accident Severity Classifier", | |
| description="Upload a short crash clip to classify severity (minor / moderate / major).", | |
| api_name="predict", | |
| flagging_mode="never", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |