Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import zipfile
|
3 |
+
import importlib.util
|
4 |
+
import os
|
5 |
+
import shutil
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
REMOTE_CODE_URL = os.environ.get("api_url")
|
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()
|