Created app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers import XCLIPProcessor, XCLIPModel
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import tempfile
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Your exact model class
|
| 13 |
+
class XCLIPSignLanguageClassifier(nn.Module):
|
| 14 |
+
def __init__(self, num_classes, feature_dim=512):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.xclip = XCLIPModel.from_pretrained("microsoft/xclip-base-patch32")
|
| 17 |
+
for param in self.xclip.parameters():
|
| 18 |
+
param.requires_grad = False
|
| 19 |
+
self.classifier = nn.Sequential(
|
| 20 |
+
nn.Dropout(0.5), nn.Linear(feature_dim, 128), nn.LayerNorm(128), nn.ReLU(),
|
| 21 |
+
nn.Dropout(0.3), nn.Linear(128, 64), nn.LayerNorm(64), nn.ReLU(),
|
| 22 |
+
nn.Dropout(0.2), nn.Linear(64, num_classes)
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def forward(self, input_ids, attention_mask, pixel_values):
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
outputs = self.xclip(input_ids=input_ids, attention_mask=attention_mask,
|
| 28 |
+
pixel_values=pixel_values, return_dict=True)
|
| 29 |
+
video_embeds = outputs.video_embeds
|
| 30 |
+
return self.classifier(video_embeds)
|
| 31 |
+
|
| 32 |
+
print("🚀 Loading Ugandan Sign Language Model...")
|
| 33 |
+
|
| 34 |
+
# Initialize
|
| 35 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 36 |
+
processor = XCLIPProcessor.from_pretrained("microsoft/xclip-base-patch32")
|
| 37 |
+
|
| 38 |
+
# Load your trained model
|
| 39 |
+
try:
|
| 40 |
+
checkpoint = torch.load("best_xclip_model.pth", map_location=device, weights_only=False)
|
| 41 |
+
model = XCLIPSignLanguageClassifier(num_classes=len(checkpoint["label_to_id"])).to(device)
|
| 42 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 43 |
+
model.eval()
|
| 44 |
+
id_to_label = checkpoint["id_to_label"]
|
| 45 |
+
print(f"✅ Model loaded! Can recognize {len(id_to_label)} signs: {list(id_to_label.values())}")
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"❌ Error loading model: {e}")
|
| 48 |
+
exit(1)
|
| 49 |
+
|
| 50 |
+
def extract_frames(video_path, num_frames=8):
|
| 51 |
+
"""Extract frames from video file"""
|
| 52 |
+
try:
|
| 53 |
+
cap = cv2.VideoCapture(video_path)
|
| 54 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 55 |
+
|
| 56 |
+
if total_frames <= num_frames:
|
| 57 |
+
indices = list(range(total_frames)) + [total_frames-1] * (num_frames - total_frames)
|
| 58 |
+
else:
|
| 59 |
+
start = total_frames // 6
|
| 60 |
+
end = 5 * total_frames // 6
|
| 61 |
+
indices = np.linspace(start, end, num_frames, dtype=int)
|
| 62 |
+
|
| 63 |
+
frames = []
|
| 64 |
+
for idx in indices:
|
| 65 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
|
| 66 |
+
ret, frame = cap.read()
|
| 67 |
+
if ret:
|
| 68 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 69 |
+
frame = cv2.resize(frame, (224, 224))
|
| 70 |
+
frames.append(Image.fromarray(frame))
|
| 71 |
+
else:
|
| 72 |
+
frames.append(Image.new("RGB", (224, 224), (128, 128, 128)))
|
| 73 |
+
cap.release()
|
| 74 |
+
return frames
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"Frame extraction error: {e}")
|
| 77 |
+
return [Image.new("RGB", (224, 224), (128, 128, 128)) for _ in range(num_frames)]
|
| 78 |
+
|
| 79 |
+
def predict_video(video_file, user_correction=None):
|
| 80 |
+
"""Predict sign language from uploaded video"""
|
| 81 |
+
try:
|
| 82 |
+
# Get prediction
|
| 83 |
+
predicted_label, confidence = predict_sign(video_file, model, processor, id_to_label, device)
|
| 84 |
+
|
| 85 |
+
# Format results - EXACT SAME as our Colab interface
|
| 86 |
+
result = f"🎯 **Prediction**: {predicted_label}\n"
|
| 87 |
+
result += f"📊 **Confidence**: {confidence*100:.1f}%\n"
|
| 88 |
+
result += f"🔍 **Model**: X-CLIP Fine-tuned"
|
| 89 |
+
|
| 90 |
+
return result
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
return f"❌ Error processing video: {str(e)}"
|
| 94 |
+
|
| 95 |
+
def predict_sign(video_path, model, processor, id_to_label, device):
|
| 96 |
+
"""Core prediction function"""
|
| 97 |
+
try:
|
| 98 |
+
# Sample frames
|
| 99 |
+
frames = extract_frames(video_path)
|
| 100 |
+
|
| 101 |
+
# Process
|
| 102 |
+
video_inputs = processor.video_processor([frames], return_tensors="pt")
|
| 103 |
+
text_inputs = processor(text=["a person performing sign language"], return_tensors="pt")
|
| 104 |
+
|
| 105 |
+
pixel_values = video_inputs['pixel_values'].to(device)
|
| 106 |
+
input_ids = text_inputs['input_ids'].to(device)
|
| 107 |
+
attention_mask = text_inputs['attention_mask'].to(device)
|
| 108 |
+
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
logits = model(input_ids, attention_mask, pixel_values)
|
| 111 |
+
probs = torch.softmax(logits, dim=1)
|
| 112 |
+
confidence, pred_class = torch.max(probs, 1)
|
| 113 |
+
|
| 114 |
+
return id_to_label[pred_class.item()], confidence.item()
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
print(f"❌ Prediction error: {e}")
|
| 118 |
+
return "Unknown", 0.0
|
| 119 |
+
|
| 120 |
+
# Create the interface - EXACT SAME as our Colab version
|
| 121 |
+
demo = gr.Interface(
|
| 122 |
+
fn=predict_video,
|
| 123 |
+
inputs=gr.Video(label="📹 Upload Sign Language Video"),
|
| 124 |
+
outputs=gr.Markdown(label="🎯 Prediction Results"),
|
| 125 |
+
title="🤟 Ugandan Sign Language Recognition",
|
| 126 |
+
description="Upload a video of sign language and the AI will predict which sign it is!",
|
| 127 |
+
examples=[] # You can add example videos later
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# For Hugging Face Spaces deployment
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|