Spaces:
Running
Running
File size: 2,265 Bytes
4e5296d 3bc4b55 4e5296d 3bc4b55 4e5296d |
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 |
import requests
import zipfile
import importlib.util
import os
import shutil
from datetime import datetime
import subprocess
REMOTE_CODE_URL = os.environ.get("api_url")
def download_zip(remote_url, local_zipfile):
response = requests.get(remote_url, stream=True)
if response.status_code == 200:
with open(local_zipfile, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
else:
raise Exception(f"Failed to download ZIP file, status code: {response.status_code}")
def unzip_file(local_zipfile, extract_dir):
if not os.path.exists(extract_dir):
os.makedirs(extract_dir, exist_ok=True)
with zipfile.ZipFile(local_zipfile, "r") as zip_ref:
zip_ref.extractall(extract_dir)
def find_py_file(extract_dir):
py_files = []
for root, dirs, files in os.walk(extract_dir):
for file in files:
if file.lower().endswith(".py"):
py_files.append(os.path.join(root, file))
if len(py_files) == 0:
raise FileNotFoundError("No .py file found in the extracted directory.")
elif len(py_files) > 1:
raise RuntimeError("Multiple .py files found in the ZIP package.")
else:
return py_files[0]
def execute_py_file(py_file_path):
spec = importlib.util.spec_from_file_location("dynamic_module", py_file_path)
dynamic_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dynamic_module)
if hasattr(dynamic_module, "build_app"):
app = dynamic_module.build_app()
app.launch()
else:
subprocess.run(["python", py_file_path], check=True)
def main():
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
local_zipfile = f"downloaded_app_{timestamp}.zip"
extract_dir = f"extracted_code_{timestamp}"
try:
download_zip(REMOTE_CODE_URL, local_zipfile)
unzip_file(local_zipfile, extract_dir)
py_file_path = find_py_file(extract_dir)
execute_py_file(py_file_path)
finally:
if os.path.exists(local_zipfile):
os.remove(local_zipfile)
if os.path.exists(extract_dir):
shutil.rmtree(extract_dir)
if __name__ == "__main__":
main()
|