ashen97 commited on
Commit
05251a7
·
verified ·
1 Parent(s): c75989a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -0
app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ultralytics import YOLO
3
+ import os
4
+ import time
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ # Setup model from Hugging Face
8
+ REPO_ID = "ashen97/fabric-defect-yolo"
9
+ MODEL_FILES = {
10
+ "YOLOv8n": "YOLOv8n.pt",
11
+ "YOLOv8s": "YOLOv8s.pt",
12
+ "YOLOv11": "YOLOv11.pt"
13
+ }
14
+
15
+ # Verify models
16
+ print("Checking models...")
17
+ MODEL_PATHS = {}
18
+
19
+ try:
20
+ for display_name, filename in MODEL_FILES.items():
21
+ # Download model to local cache
22
+ cached_path = hf_hub_download(repo_id=REPO_ID, filename=filename)
23
+ MODEL_PATHS[display_name] = cached_path
24
+ print(f"✅ Loaded: {display_name}")
25
+ except Exception as e:
26
+ print(f"⚠️ Note: Could not verify Hugging Face models ({e}).")
27
+
28
+ # Prediction function
29
+ def detect_defects(input_video, model_name, conf_level):
30
+ try:
31
+ if input_video is None:
32
+ raise gr.Error("Please upload a video first!")
33
+
34
+ # Create output folder
35
+ timestamp = int(time.time())
36
+
37
+ output_dir = f"gradio_results_{timestamp}"
38
+ os.makedirs(output_dir, exist_ok=True)
39
+
40
+ # Load Model
41
+ if model_name in MODEL_PATHS:
42
+ model_path = MODEL_PATHS[model_name]
43
+ else:
44
+ raise gr.Error(f"Model file for {model_name} not found!")
45
+
46
+ model = YOLO(model_path)
47
+
48
+ # Run Prediction
49
+ print(f"Processing video with {model_name}...")
50
+ results = model.predict(
51
+ source = input_video,
52
+ save = True,
53
+ conf = conf_level,
54
+ project = output_dir,
55
+ name = "run",
56
+ verbose = False
57
+ )
58
+
59
+ # Find Output Video
60
+ save_dir = results[0].save_dir
61
+ files = os.listdir(save_dir)
62
+
63
+ # Verify video for .avi or .mp4
64
+ video_file = next((f for f in files if f.endswith(('.avi', '.mp4'))), None)
65
+
66
+ if not video_file:
67
+ raise gr.Error("YOLO finished but no video file was saved.")
68
+
69
+ full_video_path = os.path.join(save_dir, video_file)
70
+
71
+ # Convert to .mp4 for browser compatibility
72
+ output_mp4 = full_video_path.replace(".avi", "_converted.mp4")
73
+
74
+ # FFmpeg command
75
+ if not os.path.exists(output_mp4):
76
+ os.system(f"ffmpeg -y -loglevel panic -i '{full_video_path}' -vcodec libx264 '{output_mp4}'")
77
+
78
+ return output_mp4
79
+
80
+ # Show error in UI
81
+ except Exception as e:
82
+ print(f"Error Details: {str(e)}")
83
+ raise gr.Error(f"System Error: {str(e)}")
84
+
85
+ # Build UI
86
+ inputs = [
87
+ gr.Video(label="Input Video"),
88
+ gr.Dropdown(choices=list(MODEL_FILES.keys()), value=list(MODEL_FILES.keys())[0], label="Model Variant"),
89
+ gr.Slider(0.0, 1.0, value=0.25, step=0.05, label="Confidence Threshold")
90
+ ]
91
+
92
+ # Run UI
93
+ demo = gr.Interface(
94
+ fn = detect_defects,
95
+ inputs = inputs,
96
+ outputs = gr.Video(label="Predicted Output"),
97
+ title = "Fabric Defect Detection System",
98
+ description = "Upload a video to detect defects in real-time.",
99
+ theme = "soft"
100
+ )
101
+
102
+ # Launch
103
+ if __name__ == "__main__":
104
+ demo.launch()