SuriRaja commited on
Commit
b8ff751
·
verified ·
1 Parent(s): 2d9fabf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -42
app.py CHANGED
@@ -1,24 +1,20 @@
1
- import gradio as gr
2
- import torch
3
- import numpy as np
4
  import cv2
 
 
 
 
5
  from PIL import Image
6
- from transformers import AutoImageProcessor, AutoModelForVideoClassification, ViTForImageClassification
7
 
8
- # Load video model and processor
9
- video_processor = AutoImageProcessor.from_pretrained("facebook/timesformer-base-finetuned-k400")
10
- video_model = AutoModelForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
11
-
12
- # Load image model and processor
13
- image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
14
- image_model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
15
 
16
  def extract_frames(video_path, num_frames=8):
17
  cap = cv2.VideoCapture(video_path)
18
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
19
  frames = []
20
- frame_indices = np.linspace(0, total_frames - 1, num_frames).astype(int)
21
- for idx in frame_indices:
22
  cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
23
  ret, frame = cap.read()
24
  if not ret:
@@ -29,43 +25,35 @@ def extract_frames(video_path, num_frames=8):
29
  cap.release()
30
  return frames
31
 
 
 
 
 
 
32
  def predict(file):
33
  if file is None:
34
- return "Please upload a file.", None
35
 
36
- path = file.name
37
  video_exts = [".mp4", ".avi", ".mov", ".mkv"]
38
-
39
- if any(path.lower().endswith(ext) for ext in video_exts):
40
- # Video
41
- frames = extract_frames(path)
42
- inputs = video_processor(frames, return_tensors="pt")
43
  with torch.no_grad():
44
- outputs = video_model(**inputs)
45
  logits = outputs.logits
46
- pred_id = torch.argmax(logits, dim=-1).item()
47
- label = video_model.config.id2label[pred_id]
48
- confidence = torch.nn.functional.softmax(logits, dim=-1)[0, pred_id].item()
49
- return f"Video Prediction: {label} (Confidence: {confidence:.2f})", path
50
  else:
51
- # Image
52
- image = Image.open(path).convert("RGB")
53
- inputs = image_processor(images=image, return_tensors="pt")
54
  with torch.no_grad():
55
  outputs = image_model(**inputs)
56
  logits = outputs.logits
57
- pred_id = torch.argmax(logits, dim=-1).item()
58
- label = image_model.config.id2label[pred_id]
59
- confidence = torch.nn.functional.softmax(logits, dim=-1)[0, pred_id].item()
60
- return f"Image Prediction: {label} (Confidence: {confidence:.2f})", None
61
-
62
- iface = gr.Interface(
63
- fn=predict,
64
- inputs=gr.File(file_types=[".mp4", ".avi", ".mov", ".mkv", ".jpg", ".jpeg", ".png"]),
65
- outputs=[gr.Textbox(label="Prediction"), gr.Video(label="Uploaded Video")],
66
- title="Image and Video Classification",
67
- description="Upload an image or video. Video predictions use manual frame extraction to avoid decord dependency."
68
- )
69
 
70
- if __name__ == "__main__":
71
- iface.launch()
 
 
 
 
1
  import cv2
2
+ import numpy as np
3
+ import torch
4
+ from transformers import AutoImageProcessor, AutoModelForVideoClassification
5
+ import gradio as gr
6
  from PIL import Image
 
7
 
8
+ # Use AutoModelForVideoClassification which is generic and supports TimeSformer
9
+ processor = AutoImageProcessor.from_pretrained("facebook/timesformer-base-finetuned-k400")
10
+ model = AutoModelForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
 
 
 
 
11
 
12
  def extract_frames(video_path, num_frames=8):
13
  cap = cv2.VideoCapture(video_path)
14
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
15
  frames = []
16
+ frame_idxs = np.linspace(0, total_frames - 1, num_frames).astype(int)
17
+ for idx in frame_idxs:
18
  cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
19
  ret, frame = cap.read()
20
  if not ret:
 
25
  cap.release()
26
  return frames
27
 
28
+ # Image classification for fallback
29
+ image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
30
+ image_model = torch.hub.load('pytorch/vision:v0.14.0', 'vit_b_16', pretrained=True)
31
+ image_model.eval()
32
+
33
  def predict(file):
34
  if file is None:
35
+ return "Please upload a file."
36
 
37
+ filepath = file.name
38
  video_exts = [".mp4", ".avi", ".mov", ".mkv"]
39
+ if any(filepath.lower().endswith(ext) for ext in video_exts):
40
+ frames = extract_frames(filepath)
41
+ inputs = processor(frames, return_tensors="pt")
 
 
42
  with torch.no_grad():
43
+ outputs = model(**inputs)
44
  logits = outputs.logits
45
+ pred_idx = torch.argmax(logits, dim=-1).item()
46
+ label = model.config.id2label[pred_idx]
47
+ prob = torch.nn.functional.softmax(logits, dim=-1)[0, pred_idx].item()
48
+ return f"Video Prediction: {label} (Confidence: {prob:.2f})"
49
  else:
50
+ image = Image.open(filepath).convert("RGB")
51
+ inputs = image_processor(image, return_tensors="pt")
 
52
  with torch.no_grad():
53
  outputs = image_model(**inputs)
54
  logits = outputs.logits
55
+ pred_idx = torch.argmax(logits, dim=-1).item()
56
+ return f"Image Prediction index: {pred_idx} (Raw model, no labels)"
 
 
 
 
 
 
 
 
 
 
57
 
58
+ iface = gr.Interface(fn=predict, inputs=gr.File(file_types=[".mp4", ".avi", ".mov", ".mkv", ".jpg", ".png"]), outputs="text")
59
+ iface.launch()