File size: 4,869 Bytes
21f0a5b
 
 
b579390
c91adfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76de74c
f6306b2
dc25230
 
c91adfa
 
 
 
 
 
f6306b2
c91adfa
 
 
 
 
dc25230
c91adfa
 
 
 
 
 
 
 
f6306b2
c91adfa
 
 
 
 
 
76de74c
c91adfa
 
 
76de74c
 
c91adfa
76de74c
c91adfa
76de74c
b42d845
c91adfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6306b2
c91adfa
 
b579390
c91adfa
b579390
 
c91adfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c24c808
 
 
c91adfa
 
c24c808
 
b42d845
c91adfa
 
 
 
 
c24c808
 
5805ae0
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import gradio as gr
import subprocess
import os
import shutil
import tempfile
from datetime import datetime
from huggingface_hub import (
    login,
    hf_hub_download,
    upload_file,
    upload_folder,
    HfApi,
)

# -------------------------------------------------
# Cấu hình (đặt các biến môi trường trước khi chạy)
# -------------------------------------------------
REPO_ID = os.getenv("HFPATH")          # ví dụ: "username/dataset-name"
HF_TOKEN = os.getenv("MAGIC")          # token Hugging Face của bạn
login(HF_TOKEN)

api = HfApi()


# -------------------------------------------------
# Hàm phụ: tải xuống tất cả file trong một subfolder
# -------------------------------------------------
def download_from_hf(subfolder: str):
    """Trả về danh sách đường dẫn cục bộ của các file trong `subfolder`."""
    downloaded_files = []

    # Lấy danh sách mọi file trong repo dataset
    all_files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset")

    # Chỉ giữ lại những file bắt đầu bằng subfolder yêu cầu
    for file in all_files:
        if file.startswith(f"{subfolder}/"):
            local_path = hf_hub_download(
                repo_id=REPO_ID,
                filename=file,
                repo_type="dataset",
            )
            downloaded_files.append(local_path)

    return downloaded_files


# -------------------------------------------------
# Hàm phụ: tải lên một file đơn lẻ vào thư mục theo ngày
# -------------------------------------------------
def upload_to_hf(filepath: str):
    filename = os.path.basename(filepath)
    subfolder = datetime.now().strftime("%Y%m%d")
    path_in_repo = f"{subfolder}/{filename}"

    upload_file(
        path_or_fileobj=filepath,
        path_in_repo=api,
        repo_id=REPO_ID,
        repo_type="dataset",
    )
    return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{path_in_repo}"


# -------------------------------------------------
# Hàm phụ: tải lên toàn bộ thư mục vào thư mục theo ngày
# -------------------------------------------------
def upload_folder_to_hf(folder_path: str):
    subfolder = datetime.now().strftime("%Y%m%d")
    upload_folder(
        folder_path=folder_path,
        path_in_repo=subfolder,
        repo_id=REPO_ID,
        repo_type="dataset",
    )
    return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{subfolder}"


# -------------------------------------------------
# Hàm chính được Gradio gọi
# -------------------------------------------------
def run_scripts(subfolder: str, source):
    """
    1. Tải về các file mục tiêu từ `subfolder`.
    2. Chạy `run.py` cho mỗi file, tạo file output.
    3. Sao chép các output vào thư mục tạm.
    4. Tải lên thư mục tạm lên Hugging Face.
    Trả về danh sách tên file output.
    """
    output_files = []
    target_files = download_from_hf(subfolder)

    # Thư mục tạm để gom kết quả
    with tempfile.TemporaryDirectory() as temp_dir:
        print(f"Thư mục tạm được tạo: {temp_dir}")

        for target_file in target_files:
            # Giữ nguyên phần mở rộng của file gốc
            _, ext = os.path.splitext(target_file)
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            output_path = f"output_{timestamp}{ext}"

            # Lệnh gọi script swap mặt
            cmd = [
                "python3",
                "run.py",
                "-s",
                source.name,
                "-t",
                target_file,
                "-o",
                output_path,
                "--frame-processor",
                "face_swapper",
                "--many-faces",
            ]

            # Thực thi, sẽ ném lỗi nếu có vấn đề
            subprocess.run(cmd, check=True)

            output_files.append(output_path)
            print(f"Tạo: {output_path}")

            # Sao chép vào thư mục tạm
            dest_path = os.path.join(temp_dir, os.path.basename(output_path))
            shutil.copy(output_path, dest_path)
            print(f"Đã sao chép {output_path}{dest_path}")

        # Tải lên toàn bộ thư mục tạm
        upload_folder_to_hf(temp_dir)

    return output_files


# -------------------------------------------------
# Giao diện Gradio
# -------------------------------------------------
iface = gr.Interface(
    fn=run_scripts,
    inputs=[
        "text",   # tên subfolder
        "file",   # ảnh nguồn
    ],
    outputs="files",
    title="Face Swapper",
    description=(
        "Nhập tên subfolder trong dataset và tải lên ảnh nguồn để thực hiện "
        "đổi mặt."
    ),
    live=False,
)

iface.launch()