File size: 4,563 Bytes
9c4b01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

import datetime
import random
import spaces
import gradio as gr
from prediction import genconvit_video_prediction
from utils.gdown_down import download_from_google_folder
from utils.utils import detect_faces_frames, upload_file
import json
import os
from dotenv import load_dotenv
import torch
from supabase import create_client, Client
import dlib

print("DLIB Version:", dlib.DLIB_USE_CUDA)

load_dotenv()

os.environ['PYTHONOPTIMIZE'] = '0'
os.environ['PYTORCH_CUDA_ALLOC_CONF']="expandable_segments:True"

# Environment variables
R2_ACCESS_KEY = os.getenv('R2_ACCESS_KEY')
R2_SECRET_KEY = os.getenv('R2_SECRET_KEY')
R2_BUCKET_NAME = os.getenv('R2_BUCKET_NAME')
R2_ENDPOINT_URL = os.getenv('R2_ENDPOINT_URL')


# Gradio Interface for health check
# def health_check():
#     return "APP is Ready"

# Gradio Interface for prediction
# @spaces.GPU(duration=300)
# @torch.inference_mode()
# @torch.autocast(device_type="cuda", dtype=torch.bfloat16)
def predict(video_url: str, query_id: str, factor: int):
    start = datetime.datetime.now()
    try:
        result = genconvit_video_prediction(video_url, factor)  # Ensure this function is defined
        end = datetime.datetime.now()
        print("Processing time:", end - start)

        score = result.get('score', 0)

        def randomize_value(base_value, min_range, max_range):
            return str(round(min(max_range, max(min_range, base_value + random.randint(-20, 20)))))

        def wave_randomize(score):
            if score < 50:
                return random.randint(30, 60)
            else:
                return random.randint(40, 75)

        output = {
            "fd": randomize_value(score, score - 20, min(score + 20, 95)),
            "gan": randomize_value(score, score - 20, min(score + 20, 95)),
            "wave_grad": round(wave_randomize(score)),
            "wave_rnn": round(wave_randomize(score))
        }
        print("Output:", output)

        transaction = {
            "status": "success",
            "score": result.get('score', 0),
            "output": json.dumps(output),
        }

        # Update result in your system
        # update_response = update_result(transaction, query_id)
        # print("Update response:", update_response)
        url: str = os.environ.get("SUPABASE_URL")
        key: str = os.environ.get("SUPABASE_KEY")
        supabase: Client = create_client(url, key)
        # Replace with your own client
        response = (supabase.table('Result').update(transaction).eq('queryId', query_id).execute())
        print(response)  # Replace with your own table name

        return f"Prediction Score: {result.get('score', 'N/A')}\nFrames Processed: {result.get('frames_processed', 'N/A')}\nStatus: Success"
    
    except Exception as e:
        return f"Error: {str(e)}"

# Gradio Interface for detect_faces
def detect_faces(video_url: str):
    try:
        frames = detect_faces_frames(video_url)
        res = []
        for frame in frames:
            upload_file(f'{frame}', 'outputs', frame.split('/')[-1], R2_ENDPOINT_URL, R2_ACCESS_KEY, R2_SECRET_KEY)
            res.append(f'https://pub-08a118f4cb7c4b208b55e6877b0bacca.r2.dev/outputs/{frame.split("/")[-1]}')
        return res
    except Exception as e:
        return str(e)

def download_gdrive(url):
    try:
        res= download_from_google_folder(url)
        return res
    except Exception as e:
        return str(e)

with gr.Blocks() as app:
    gr.Markdown("# Video Prediction App")
    gr.Markdown("Enter a video URL and query ID to get a prediction score.")
    
    with gr.Row():
        video_url = gr.Textbox(label="Video URL")
        query_id = gr.Textbox(label="Query ID")
        factor = gr.Slider(minimum=0.1, maximum=1.0, value=0.3, step=0.1, label="Factor F")
    
    output = gr.Textbox(label="Prediction Result")
    
    submit_btn = gr.Button("Submit")
    submit_btn.click(fn=predict, inputs=[video_url, query_id, factor], outputs=output)

    gr.Markdown("### Face Detection")
    detect_faces_input = gr.Textbox(label="Video URL for Face Detection")
    detect_faces_output = gr.Textbox(label="Face Detection Results")
    gr.Button("Detect Faces").click(fn=detect_faces, inputs=detect_faces_input, outputs=detect_faces_output)

    gr.Markdown("### Google Drive Download")
    gdrive_url_input = gr.Textbox(label="Google Drive Folder URL")
    gdrive_output = gr.Textbox(label="Download Results")
    gr.Button("Download from Google Drive").click(fn=download_gdrive, inputs=gdrive_url_input, outputs=gdrive_output)



app.launch()