File size: 4,385 Bytes
0c78d95
 
98173c8
371c310
0c78d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371c310
 
 
 
 
 
 
 
98173c8
 
 
 
 
 
 
 
 
 
0c78d95
98173c8
 
 
 
 
 
 
 
 
 
 
 
0c78d95
98173c8
 
 
0c78d95
98173c8
 
 
 
0c78d95
 
98173c8
 
 
 
 
0c78d95
 
 
98173c8
0c78d95
 
 
 
98173c8
 
 
0c78d95
 
 
 
 
 
 
 
98173c8
0c78d95
98173c8
 
 
 
 
 
 
 
 
 
 
 
 
0c78d95
98173c8
0c78d95
 
 
98173c8
 
 
 
 
 
 
 
 
 
 
0c78d95
 
 
 
 
 
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
133
134
135
import os

from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import JSONResponse
from supabase import create_client

from src.components.vidgen import VideoCreator

supabase_url = os.getenv('SUPABASE_URL')
supabase_key = os.getenv('SUPABASE_KEY')
supabase = create_client(supabase_url, supabase_key)
app = FastAPI()

RESOURCES_DIR = "resources"
os.makedirs(RESOURCES_DIR, exist_ok=True)


def upload_to_supabase(video_path, bucket_name="JewelmirrorVideoGeneration"):
    try:
        with open(video_path, 'rb') as f:
            file_name = os.path.basename(video_path)
            supabase.storage.from_(bucket_name).upload(file_name, f)

            public_url = supabase.storage.from_(bucket_name).get_public_url(file_name)
            return public_url
    except Exception as e:
        print(f"Error uploading to Supabase: {str(e)}")
        return None


class VideoGenerator(BaseModel):
    necklace_image: str
    necklace_try_on_output_images: list[str]
    clothing_output_images: list[str]
    makeup_output_images: list[str]
    store_name: str


import requests
import tempfile


def download_image(url):
    """
    Download an image from the web and save it as a temporary file.
    :param url: URL of the image.
    :return: Path to the temporary file.
    """
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()

        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
        with open(temp_file.name, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        return temp_file.name
    except Exception as e:
        print(f"Error downloading image from {url}: {str(e)}")
        return None


@app.post("/create-video/")
async def create_video(request: VideoGenerator):
    try:
        temp_files = {
            'necklace': download_image(request.necklace_image),
            'necklace_tryon': [download_image(url) for url in request.necklace_try_on_output_images],
            'clothing': [download_image(url) for url in request.clothing_output_images],
            'makeup': [download_image(url) for url in request.makeup_output_images]
        }

        if any(file is None for files in temp_files.values() for file in
               (files if isinstance(files, list) else [files])):
            return JSONResponse(content={"status": "error", "message": "Failed to download all required images."},
                                status_code=400)

        intro_path = f"{RESOURCES_DIR}/intro/ChamundiJewelsMandir_intro.mp4"
        output_path = f"{RESOURCES_DIR}/temp_video/video_{os.urandom(8).hex()}.mp4"
        font_path = f"{RESOURCES_DIR}/fonts/PlayfairDisplay-VariableFont_wght.ttf"
        audio_path = f"{RESOURCES_DIR}/audio/TraditionalIndianVlogMusic.mp3"

        video_creator = VideoCreator(
            intro_video_path=intro_path,
            necklace_image=temp_files['necklace'],
            nto_outputs=temp_files['necklace_tryon'],
            nto_cto_outputs=temp_files['clothing'],
            makeup_outputs=temp_files['makeup'],
            font_path=font_path,
            output_path=output_path,
            audio_path=audio_path
        )

        # Generate video
        video_creator.create_final_video()

        # Upload to Supabase
        url = upload_to_supabase(video_path=output_path)
        response = {
            "status": "success",
            "message": "Video created successfully",
            "public_url": url
        }

        for files in temp_files.values():
            if isinstance(files, list):
                for file in files:
                    if os.path.exists(file):
                        os.unlink(file)
            elif os.path.exists(files):
                os.unlink(files)

        os.remove(output_path)
        return JSONResponse(content=response, status_code=200)

    except Exception as e:
        raise e


@app.get("/resources")
async def get_infromation():
    music = os.listdir(RESOURCES_DIR + "/audio")
    fonts = os.listdir(RESOURCES_DIR + "/fonts")
    intro = os.listdir(RESOURCES_DIR + "/intro")

    json = {"music": music, "fonts": fonts, "intro": intro}
    return JSONResponse(content=json, status_code=200)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)