Spaces:
Running
Running
| 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() | |