mr2along commited on
Commit
c91adfa
·
verified ·
1 Parent(s): b579390

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -59
app.py CHANGED
@@ -1,89 +1,153 @@
1
  import gradio as gr
2
  import subprocess
3
  import os
4
- from datetime import datetime
5
- from huggingface_hub import login, hf_hub_download, upload_file, HfApi, upload_folder
6
- import tempfile
7
  import shutil
8
- # --- Config ---
9
- REPO_ID = os.environ.get("HFPATH")
10
- HF_TOKEN = os.environ.get("MAGIC")
 
 
 
 
 
 
 
 
 
 
 
 
11
  login(HF_TOKEN)
12
 
13
- # --- Download function ---
14
  api = HfApi()
15
 
16
- # --- Download function ---
17
- def download_from_hf(subfolder):
 
 
 
 
18
  downloaded_files = []
19
-
20
- # List all files in the repository
21
- all_files = api.list_repo_files(repo_id=REPO_ID,repo_type="dataset")
22
-
23
- # Filter files that start with the specified subfolder
24
  for file in all_files:
25
- if file.startswith(subfolder + "/"):
26
- # Download the file
27
- downloaded_file = hf_hub_download(repo_id=REPO_ID, filename=file,repo_type="dataset" )
28
- downloaded_files.append(downloaded_file)
29
-
 
 
 
30
  return downloaded_files
31
- # --- Upload function ---
32
- def upload_to_hf(filepath):
 
 
 
 
33
  filename = os.path.basename(filepath)
34
- SUBFOLDER = datetime.now().strftime("%Y%m%d")
35
- path_in_repo = f"{SUBFOLDER}/{filename}"
 
36
  upload_file(
37
  path_or_fileobj=filepath,
38
- path_in_repo=path_in_repo,
39
  repo_id=REPO_ID,
40
- repo_type="dataset"
41
  )
42
  return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{path_in_repo}"
43
- def upload_to_fd(path):
44
- SUBFOLDER = datetime.now().strftime("%Y%m%d")
45
- upload_folder(folder_path=path,
46
- path_in_repo=SUBFOLDER,
47
- repo_id=REPO_ID,
48
- repo_type="dataset")
49
- return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{SUBFOLDER}"
50
-
51
- def run_scripts(subfolder, source):
52
- outputfile = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  target_files = download_from_hf(subfolder)
54
-
55
-
56
- # Tạo thư mục tạm và lưu file đầu ra vào đó
57
  with tempfile.TemporaryDirectory() as temp_dir:
58
- print(f"Thư mục tạm thời được tạo: {temp_dir}")
59
 
60
  for target_file in target_files:
61
- target_extension = os.path.splitext(target_file)[-1]
62
- #filename = os.path.splitext(target_file)[0]
63
- timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
64
- output_path = f"output_{timestamp}{target_extension}"
65
- cmd1 = ["python3", "run.py", "-s", source.name, "-t", target_file, "-o", output_path, "--frame-processor", "face_swapper", '--many-faces']
66
- subprocess.run(cmd1)
67
- outputfile.append(output_path)
68
- print(output_path)
69
- # Sao chép file vào thư mục tạm
70
- destination_file = os.path.join(temp_dir, os.path.basename(output_path))
71
- shutil.copy(output_path, destination_file)
72
- print(f"Đã sao chép {output_path} vào {destination_file}")
73
-
74
- # Tải lên thư mục tạm lên Hugging Face
75
- upload_to_fd(temp_dir)
76
- return outputfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  iface = gr.Interface(
78
  fn=run_scripts,
79
  inputs=[
80
- "text",
81
- "file"
82
  ],
83
  outputs="files",
84
  title="Face Swapper",
85
- description="Enter a subfolder name from the dataset and upload a source image to swap faces.",
86
- live=False
 
 
 
87
  )
88
 
89
  iface.launch()
 
1
  import gradio as gr
2
  import subprocess
3
  import os
 
 
 
4
  import shutil
5
+ import tempfile
6
+ from datetime import datetime
7
+ from huggingface_hub import (
8
+ login,
9
+ hf_hub_download,
10
+ upload_file,
11
+ upload_folder,
12
+ HfApi,
13
+ )
14
+
15
+ # -------------------------------------------------
16
+ # Cấu hình (đặt các biến môi trường trước khi chạy)
17
+ # -------------------------------------------------
18
+ REPO_ID = os.getenv("HFPATH") # ví dụ: "username/dataset-name"
19
+ HF_TOKEN = os.getenv("MAGIC") # token Hugging Face của bạn
20
  login(HF_TOKEN)
21
 
 
22
  api = HfApi()
23
 
24
+
25
+ # -------------------------------------------------
26
+ # Hàm phụ: tải xuống tất cả file trong một subfolder
27
+ # -------------------------------------------------
28
+ def download_from_hf(subfolder: str):
29
+ """Trả về danh sách đường dẫn cục bộ của các file trong `subfolder`."""
30
  downloaded_files = []
31
+
32
+ # Lấy danh sách mọi file trong repo dataset
33
+ all_files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset")
34
+
35
+ # Chỉ giữ lại những file bắt đầu bằng subfolder yêu cầu
36
  for file in all_files:
37
+ if file.startswith(f"{subfolder}/"):
38
+ local_path = hf_hub_download(
39
+ repo_id=REPO_ID,
40
+ filename=file,
41
+ repo_type="dataset",
42
+ )
43
+ downloaded_files.append(local_path)
44
+
45
  return downloaded_files
46
+
47
+
48
+ # -------------------------------------------------
49
+ # Hàm phụ: tải lên một file đơn lẻ vào thư mục theo ngày
50
+ # -------------------------------------------------
51
+ def upload_to_hf(filepath: str):
52
  filename = os.path.basename(filepath)
53
+ subfolder = datetime.now().strftime("%Y%m%d")
54
+ path_in_repo = f"{subfolder}/{filename}"
55
+
56
  upload_file(
57
  path_or_fileobj=filepath,
58
+ path_in_repo=api,
59
  repo_id=REPO_ID,
60
+ repo_type="dataset",
61
  )
62
  return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{path_in_repo}"
63
+
64
+
65
+ # -------------------------------------------------
66
+ # Hàm phụ: tải lên toàn bộ thư mục vào thư mục theo ngày
67
+ # -------------------------------------------------
68
+ def upload_folder_to_hf(folder_path: str):
69
+ subfolder = datetime.now().strftime("%Y%m%d")
70
+ upload_folder(
71
+ folder_path=folder_path,
72
+ path_in_repo=subfolder,
73
+ repo_id=REPO_ID,
74
+ repo_type="dataset",
75
+ )
76
+ return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{subfolder}"
77
+
78
+
79
+ # -------------------------------------------------
80
+ # Hàm chính được Gradio gọi
81
+ # -------------------------------------------------
82
+ def run_scripts(subfolder: str, source):
83
+ """
84
+ 1. Tải về các file mục tiêu từ `subfolder`.
85
+ 2. Chạy `run.py` cho mỗi file, tạo file output.
86
+ 3. Sao chép các output vào thư mục tạm.
87
+ 4. Tải lên thư mục tạm lên Hugging Face.
88
+ Trả về danh sách tên file output.
89
+ """
90
+ output_files = []
91
  target_files = download_from_hf(subfolder)
92
+
93
+ # Thư mục tạm để gom kết quả
 
94
  with tempfile.TemporaryDirectory() as temp_dir:
95
+ print(f"Thư mục tạm được tạo: {temp_dir}")
96
 
97
  for target_file in target_files:
98
+ # Giữ nguyên phần mở rộng của file gốc
99
+ _, ext = os.path.splitext(target_file)
100
+ timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
101
+ output_path = f"output_{timestamp}{ext}"
102
+
103
+ # Lệnh gọi script swap mặt
104
+ cmd = [
105
+ "python3",
106
+ "run.py",
107
+ "-s",
108
+ source.name,
109
+ "-t",
110
+ target_file,
111
+ "-o",
112
+ output_path,
113
+ "--frame-processor",
114
+ "face_swapper",
115
+ "--many-faces",
116
+ ]
117
+
118
+ # Thực thi, sẽ ném lỗi nếu có vấn đề
119
+ subprocess.run(cmd, check=True)
120
+
121
+ output_files.append(output_path)
122
+ print(f"Tạo: {output_path}")
123
+
124
+ # Sao chép vào thư mục tạm
125
+ dest_path = os.path.join(temp_dir, os.path.basename(output_path))
126
+ shutil.copy(output_path, dest_path)
127
+ print(f"Đã sao chép {output_path} → {dest_path}")
128
+
129
+ # Tải lên toàn bộ thư mục tạm
130
+ upload_folder_to_hf(temp_dir)
131
+
132
+ return output_files
133
+
134
+
135
+ # -------------------------------------------------
136
+ # Giao diện Gradio
137
+ # -------------------------------------------------
138
  iface = gr.Interface(
139
  fn=run_scripts,
140
  inputs=[
141
+ "text", # tên subfolder
142
+ "file", # ảnh nguồn
143
  ],
144
  outputs="files",
145
  title="Face Swapper",
146
+ description=(
147
+ "Nhập tên subfolder trong dataset và tải lên ảnh nguồn để thực hiện "
148
+ "đổi mặt."
149
+ ),
150
+ live=False,
151
  )
152
 
153
  iface.launch()