Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,3 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
"""
|
| 3 |
-
示例:从远程下载一个 .zip 文件(其中含唯一的 .py 脚本),
|
| 4 |
-
使用唯一文件名和目录名,避免与已有同名文件互相覆盖。
|
| 5 |
-
下载与解压完成后,动态加载并执行其中的 Python 代码。
|
| 6 |
-
|
| 7 |
-
使用方法:
|
| 8 |
-
1. 将 REMOTE_CODE_URL 替换为实际的 ZIP 文件地址;
|
| 9 |
-
2. 运行本脚本,即可自动下载 ZIP、解压唯一的 .py 文件并执行 build_app()。
|
| 10 |
-
|
| 11 |
-
注意:
|
| 12 |
-
- ZIP 包内必须包含且只包含 1 个可执行的 .py 文件;
|
| 13 |
-
- 被执行的 .py 文件内需要有一个名为 build_app() 的函数,返回 Gradio 程序实例;
|
| 14 |
-
- 如果需要保留下载的 ZIP 及解压内容,可自行注释掉最后的清理逻辑。
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
import requests
|
| 18 |
import zipfile
|
| 19 |
import importlib.util
|
|
@@ -21,109 +5,60 @@ import os
|
|
| 21 |
import shutil
|
| 22 |
from datetime import datetime
|
| 23 |
|
| 24 |
-
# 远程 ZIP 文件地址(假设其中只含一个 .py 文件,且该文件内有 build_app() 函数)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
REMOTE_CODE_URL = os.environ.get("app_code_name")
|
| 28 |
|
| 29 |
def download_zip(remote_url, local_zipfile):
|
| 30 |
-
"""
|
| 31 |
-
从远程下载 ZIP 文件并保存到本地 local_zipfile 路径。
|
| 32 |
-
如果下载成功,则会在当前目录生成名为 local_zipfile 的文件。
|
| 33 |
-
"""
|
| 34 |
-
print(f"开始下载 ZIP 文件:{remote_url}")
|
| 35 |
response = requests.get(remote_url, stream=True)
|
| 36 |
if response.status_code == 200:
|
| 37 |
with open(local_zipfile, "wb") as f:
|
| 38 |
for chunk in response.iter_content(chunk_size=8192):
|
| 39 |
if chunk:
|
| 40 |
f.write(chunk)
|
| 41 |
-
print(f"ZIP 文件已下载至:{local_zipfile}")
|
| 42 |
else:
|
| 43 |
-
raise Exception(f"
|
| 44 |
|
| 45 |
def unzip_file(local_zipfile, extract_dir):
|
| 46 |
-
"""
|
| 47 |
-
解压 ZIP 文件到指定目录 extract_dir。
|
| 48 |
-
该函数会在 extract_dir 下创建对应的文件夹结构。
|
| 49 |
-
"""
|
| 50 |
-
print(f"开始解压 ZIP 文件:{local_zipfile}")
|
| 51 |
if not os.path.exists(extract_dir):
|
| 52 |
os.makedirs(extract_dir, exist_ok=True)
|
| 53 |
-
|
| 54 |
with zipfile.ZipFile(local_zipfile, "r") as zip_ref:
|
| 55 |
zip_ref.extractall(extract_dir)
|
| 56 |
|
| 57 |
-
print(f"ZIP 文件已解压到目录:{extract_dir}")
|
| 58 |
-
|
| 59 |
def find_py_file(extract_dir):
|
| 60 |
-
"""
|
| 61 |
-
在解压后目录中查找唯一的 .py 文件,并返回它的完整路径。
|
| 62 |
-
若未找到或找到多个,将抛出异常。
|
| 63 |
-
"""
|
| 64 |
py_files = []
|
| 65 |
for root, dirs, files in os.walk(extract_dir):
|
| 66 |
for file in files:
|
| 67 |
if file.lower().endswith(".py"):
|
| 68 |
py_files.append(os.path.join(root, file))
|
| 69 |
-
|
| 70 |
if len(py_files) == 0:
|
| 71 |
-
raise FileNotFoundError("
|
| 72 |
elif len(py_files) > 1:
|
| 73 |
-
raise RuntimeError("
|
| 74 |
else:
|
| 75 |
return py_files[0]
|
| 76 |
|
| 77 |
def execute_py_file(py_file_path):
|
| 78 |
-
"""
|
| 79 |
-
动态加载并执行指定路径下的 .py 文件。
|
| 80 |
-
要求此文件中必须含有 build_app() 函数,用于启动 Gradio 应用。
|
| 81 |
-
"""
|
| 82 |
-
print(f"正在动态加载并执行 Python 文件:{py_file_path}")
|
| 83 |
spec = importlib.util.spec_from_file_location("dynamic_module", py_file_path)
|
| 84 |
dynamic_module = importlib.util.module_from_spec(spec)
|
| 85 |
spec.loader.exec_module(dynamic_module)
|
| 86 |
-
|
| 87 |
if not hasattr(dynamic_module, "build_app"):
|
| 88 |
-
raise AttributeError("
|
| 89 |
-
|
| 90 |
-
print("调用 build_app() 启动 Gradio 应用……")
|
| 91 |
app = dynamic_module.build_app()
|
| 92 |
app.launch()
|
| 93 |
|
| 94 |
def main():
|
| 95 |
-
"""
|
| 96 |
-
主函数:
|
| 97 |
-
1. 使用唯一文件名下载 ZIP;
|
| 98 |
-
2. 使用唯一目录名解压 ZIP;
|
| 99 |
-
3. 查找唯一的 .py 文件并执行;
|
| 100 |
-
4. 运行结束后,清理下载的 .zip 与解压目录(可按需求修改)。
|
| 101 |
-
"""
|
| 102 |
-
# 为避免同名文件相互覆盖,我们使用当前时间作为后缀
|
| 103 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 104 |
local_zipfile = f"downloaded_app_{timestamp}.zip"
|
| 105 |
extract_dir = f"extracted_code_{timestamp}"
|
| 106 |
-
|
| 107 |
try:
|
| 108 |
-
# 1. 下载 ZIP 文件
|
| 109 |
download_zip(REMOTE_CODE_URL, local_zipfile)
|
| 110 |
-
|
| 111 |
-
# 2. 解压 ZIP 文件
|
| 112 |
unzip_file(local_zipfile, extract_dir)
|
| 113 |
-
|
| 114 |
-
# 3. 查找唯一的 .py 文件
|
| 115 |
py_file_path = find_py_file(extract_dir)
|
| 116 |
-
|
| 117 |
-
# 4. 动态加载并执行 .py 文件
|
| 118 |
execute_py_file(py_file_path)
|
| 119 |
-
|
| 120 |
finally:
|
| 121 |
-
# 以下为可选清理操作,可根据需求进行保留或删除
|
| 122 |
if os.path.exists(local_zipfile):
|
| 123 |
-
os.remove(local_zipfile)
|
| 124 |
if os.path.exists(extract_dir):
|
| 125 |
-
shutil.rmtree(extract_dir)
|
| 126 |
-
print("清理完毕。")
|
| 127 |
|
| 128 |
if __name__ == "__main__":
|
| 129 |
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
import zipfile
|
| 3 |
import importlib.util
|
|
|
|
| 5 |
import shutil
|
| 6 |
from datetime import datetime
|
| 7 |
|
|
|
|
|
|
|
|
|
|
| 8 |
REMOTE_CODE_URL = os.environ.get("app_code_name")
|
| 9 |
|
| 10 |
def download_zip(remote_url, local_zipfile):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
response = requests.get(remote_url, stream=True)
|
| 12 |
if response.status_code == 200:
|
| 13 |
with open(local_zipfile, "wb") as f:
|
| 14 |
for chunk in response.iter_content(chunk_size=8192):
|
| 15 |
if chunk:
|
| 16 |
f.write(chunk)
|
|
|
|
| 17 |
else:
|
| 18 |
+
raise Exception(f"Failed to download ZIP file, status code: {response.status_code}")
|
| 19 |
|
| 20 |
def unzip_file(local_zipfile, extract_dir):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
if not os.path.exists(extract_dir):
|
| 22 |
os.makedirs(extract_dir, exist_ok=True)
|
|
|
|
| 23 |
with zipfile.ZipFile(local_zipfile, "r") as zip_ref:
|
| 24 |
zip_ref.extractall(extract_dir)
|
| 25 |
|
|
|
|
|
|
|
| 26 |
def find_py_file(extract_dir):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
py_files = []
|
| 28 |
for root, dirs, files in os.walk(extract_dir):
|
| 29 |
for file in files:
|
| 30 |
if file.lower().endswith(".py"):
|
| 31 |
py_files.append(os.path.join(root, file))
|
|
|
|
| 32 |
if len(py_files) == 0:
|
| 33 |
+
raise FileNotFoundError("No .py file found in the extracted directory.")
|
| 34 |
elif len(py_files) > 1:
|
| 35 |
+
raise RuntimeError("Multiple .py files found in the ZIP package.")
|
| 36 |
else:
|
| 37 |
return py_files[0]
|
| 38 |
|
| 39 |
def execute_py_file(py_file_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
spec = importlib.util.spec_from_file_location("dynamic_module", py_file_path)
|
| 41 |
dynamic_module = importlib.util.module_from_spec(spec)
|
| 42 |
spec.loader.exec_module(dynamic_module)
|
|
|
|
| 43 |
if not hasattr(dynamic_module, "build_app"):
|
| 44 |
+
raise AttributeError("No function named build_app() found in the downloaded script.")
|
|
|
|
|
|
|
| 45 |
app = dynamic_module.build_app()
|
| 46 |
app.launch()
|
| 47 |
|
| 48 |
def main():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 50 |
local_zipfile = f"downloaded_app_{timestamp}.zip"
|
| 51 |
extract_dir = f"extracted_code_{timestamp}"
|
|
|
|
| 52 |
try:
|
|
|
|
| 53 |
download_zip(REMOTE_CODE_URL, local_zipfile)
|
|
|
|
|
|
|
| 54 |
unzip_file(local_zipfile, extract_dir)
|
|
|
|
|
|
|
| 55 |
py_file_path = find_py_file(extract_dir)
|
|
|
|
|
|
|
| 56 |
execute_py_file(py_file_path)
|
|
|
|
| 57 |
finally:
|
|
|
|
| 58 |
if os.path.exists(local_zipfile):
|
| 59 |
+
os.remove(local_zipfile)
|
| 60 |
if os.path.exists(extract_dir):
|
| 61 |
+
shutil.rmtree(extract_dir)
|
|
|
|
| 62 |
|
| 63 |
if __name__ == "__main__":
|
| 64 |
main()
|