agri / app.py
Nirbhay4's picture
Update app.py
977d2b8 verified
import gradio as gr
import os
import uuid
from video_process import process_video
import cv2
MODEL_PATH = "last.pt" # Your YOLO model
CONF_THRESHOLD = 0.2
PROCESSED_DIR = "processed_video"
DEMO_VIDEO = "demo.mp4" # Demo video file name
os.makedirs(PROCESSED_DIR, exist_ok=True)
# ---------------- VIDEO VALIDATION ----------------
def validate_video(video_path):
try:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return False, "Cannot open video file"
ret, frame = cap.read()
cap.release()
if not ret:
return False, "Cannot read video frames"
return True, "Video is valid"
except Exception as e:
return False, f"Video validation error: {str(e)}"
# ---------------- PROCESS VIDEO ----------------
def process_uploaded_video(video_path, confidence_threshold=0.2):
if video_path is None:
return "❌ No video provided", None
unique_id = str(uuid.uuid4())[:8]
output_filename = f"processed_{unique_id}.mp4"
output_path = os.path.join(PROCESSED_DIR, output_filename)
try:
is_valid, msg = validate_video(video_path)
if not is_valid:
return f"❌ Input video error: {msg}", None
print(f"Processing: {video_path}")
process_video(
input_video_path=video_path,
output_video_path=output_path,
model_path=MODEL_PATH,
conf_threshold=confidence_threshold
)
if not os.path.exists(output_path):
return "❌ Output video not created", None
file_size = os.path.getsize(output_path)
if file_size == 0:
return "❌ Output video empty", None
cap = cv2.VideoCapture(output_path)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
cap.release()
return f"βœ… Done! Frames: {frame_count}, FPS: {fps:.2f}, Size: {file_size/1024/1024:.2f} MB", output_path
except Exception as e:
return f"❌ Processing failed: {str(e)}", None
# ---------------- CLEAR STORAGE ----------------
def clear_processed_videos():
try:
for f in os.listdir(PROCESSED_DIR):
os.remove(os.path.join(PROCESSED_DIR, f))
return "βœ… Cleared processed videos"
except Exception as e:
return f"❌ Error: {str(e)}"
# ---------------- LOAD DEMO VIDEO ----------------
def load_demo():
return DEMO_VIDEO
# ---------------- UI ----------------
with gr.Blocks(title="Agriculture Land Video Segmentation", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# πŸŽ₯ Agriculture Land Video Segmentation (Drone)
Upload a video or try the **preloaded demo video**.
""")
with gr.Row():
with gr.Column():
video_input = gr.Video(
label="πŸ“ Upload Video (Demo loaded by default)",
value=DEMO_VIDEO, # Auto load demo video
height=300,
show_download_button=True
)
confidence_slider = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.2,
step=0.05,
label="🎯 Confidence Threshold"
)
with gr.Row():
process_btn = gr.Button("πŸš€ Process Video", variant="primary")
demo_btn = gr.Button("🎬 Load Demo Video")
clear_btn = gr.Button("πŸ—‘οΈ Clear Storage")
with gr.Column():
status_output = gr.Textbox(label="πŸ“Š Status", max_lines=5)
video_output = gr.Video(
label="🎬 Processed Video",
height=300,
show_download_button=True
)
# Buttons
process_btn.click(
fn=process_uploaded_video,
inputs=[video_input, confidence_slider],
outputs=[status_output, video_output],
show_progress=True
)
demo_btn.click(fn=load_demo, outputs=video_input)
clear_btn.click(fn=clear_processed_videos, outputs=status_output)
gr.Markdown("""
### πŸ’‘ Tips
- Keep video < 100MB
- Short videos process faster
- Lower confidence = more detections
""")
# ---------------- RUN ----------------
if __name__ == "__main__":
demo.launch(debug=True, show_error=True)