colin1842 commited on
Commit
6ce2d4c
1 Parent(s): 0fa4e6d

update app

Browse files
Files changed (3) hide show
  1. .gitignore +1 -0
  2. app.py +239 -0
  3. requirements.txt +21 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
app.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import subprocess
2
+ # from pathlib import Path
3
+ # def install_package_from_local_file(package_name, folder='packages'):
4
+ # """
5
+ # Installs a package from a local .whl file or a directory containing .whl files using pip.
6
+
7
+ # Parameters:
8
+ # path_to_file_or_directory (str): The path to the .whl file or the directory containing .whl files.
9
+ # """
10
+ # try:
11
+ # pth = str(Path(folder) / package_name)
12
+ # subprocess.check_call([subprocess.sys.executable, "-m", "pip", "install",
13
+ # "--no-index", # Do not use package index
14
+ # "--find-links", pth, # Look for packages in the specified directory or at the file
15
+ # package_name]) # Specify the package to install
16
+ # print(f"Package installed successfully from {pth}")
17
+ # except subprocess.CalledProcessError as e:
18
+ # print(f"Failed to install package from {pth}. Error: {e}")
19
+
20
+ # install_package_from_local_file('hoho')
21
+
22
+ import hoho; hoho.setup() # YOU MUST CALL hoho.setup() BEFORE ANYTHING ELSE
23
+ # import subprocess
24
+ # import importlib
25
+ # from pathlib import Path
26
+ # import subprocess
27
+
28
+
29
+ # ### The function below is useful for installing additional python wheels.
30
+ # def install_package_from_local_file(package_name, folder='packages'):
31
+ # """
32
+ # Installs a package from a local .whl file or a directory containing .whl files using pip.
33
+
34
+ # Parameters:
35
+ # path_to_file_or_directory (str): The path to the .whl file or the directory containing .whl files.
36
+ # """
37
+ # try:
38
+ # pth = str(Path(folder) / package_name)
39
+ # subprocess.check_call([subprocess.sys.executable, "-m", "pip", "install",
40
+ # "--no-index", # Do not use package index
41
+ # "--find-links", pth, # Look for packages in the specified directory or at the file
42
+ # package_name]) # Specify the package to install
43
+ # print(f"Package installed successfully from {pth}")
44
+ # except subprocess.CalledProcessError as e:
45
+ # print(f"Failed to install package from {pth}. Error: {e}")
46
+
47
+
48
+ # pip download webdataset -d packages/webdataset --platform manylinux1_x86_64 --python-version 38 --only-binary=:all:
49
+ # install_package_from_local_file('webdataset')
50
+ # install_package_from_local_file('tqdm')
51
+
52
+ import streamlit as st
53
+ import webdataset as wds
54
+ from tqdm import tqdm
55
+ from typing import Dict
56
+ import pandas as pd
57
+ from transformers import AutoTokenizer
58
+ import os
59
+ import time
60
+ import io
61
+ from PIL import Image as PImage
62
+ import numpy as np
63
+
64
+ from hoho.read_write_colmap import read_cameras_binary, read_images_binary, read_points3D_binary
65
+ from hoho import proc, Sample
66
+
67
+ def convert_entry_to_human_readable(entry):
68
+ out = {}
69
+ already_good = ['__key__', 'wf_vertices', 'wf_edges', 'edge_semantics', 'mesh_vertices', 'mesh_faces', 'face_semantics', 'K', 'R', 't']
70
+ for k, v in entry.items():
71
+ if k in already_good:
72
+ out[k] = v
73
+ continue
74
+ if k == 'points3d':
75
+ out[k] = read_points3D_binary(fid=io.BytesIO(v))
76
+ if k == 'cameras':
77
+ out[k] = read_cameras_binary(fid=io.BytesIO(v))
78
+ if k == 'images':
79
+ out[k] = read_images_binary(fid=io.BytesIO(v))
80
+ if k in ['ade20k', 'gestalt']:
81
+ out[k] = [PImage.open(io.BytesIO(x)).convert('RGB') for x in v]
82
+ if k == 'depthcm':
83
+ out[k] = [PImage.open(io.BytesIO(x)) for x in entry['depthcm']]
84
+ return out
85
+
86
+ import subprocess
87
+ import sys
88
+ import os
89
+
90
+ import numpy as np
91
+ os.environ['MKL_THREADING_LAYER'] = 'GNU'
92
+ os.environ['MKL_SERVICE_FORCE_INTEL'] = '1'
93
+
94
+ def install_package_from_local_file(package_name, folder='packages'):
95
+ """
96
+ Installs a package from a local .whl file or a directory containing .whl files using pip.
97
+
98
+ Parameters:
99
+ package_name (str): The name of the package to install.
100
+ folder (str): The folder where the .whl files are located.
101
+ """
102
+ try:
103
+ pth = str(Path(folder) / package_name)
104
+ subprocess.check_call([sys.executable, "-m", "pip", "install",
105
+ "--no-index", # Do not use package index
106
+ "--find-links", pth, # Look for packages in the specified directory or at the file
107
+ package_name]) # Specify the package to install
108
+ print(f"Package installed successfully from {pth}")
109
+ except subprocess.CalledProcessError as e:
110
+ print(f"Failed to install package from {pth}. Error: {e}")
111
+
112
+ def setup_environment():
113
+ # Uninstall torch if it is already installed
114
+ # packages_to_uninstall = ['torch', 'torchvision', 'torchaudio']
115
+ # for package in packages_to_uninstall:
116
+ # uninstall_package(package)
117
+ # Download required packages
118
+ # pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu116
119
+ # pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu121
120
+ # pip install torch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 --index-url https://download.pytorch.org/whl/cu121
121
+ # packages_to_download = ['torch==1.13.1', 'torchvision==0.14.1', 'torchaudio==0.13.1']
122
+ # packages_to_download = ['torch==2.1.0', 'torchvision==0.16.0', 'torchaudio==2.1.0']
123
+ # download_packages(packages_to_download, folder='packages/torch')
124
+
125
+ # Install ninja
126
+ # install_package_from_local_file('ninja', folder='packages')
127
+
128
+ # packages_to_download = ['torch==2.1.0', 'torchvision==0.16.0', 'torchaudio==2.1.0']
129
+ # download_folder = 'packages/torch'
130
+
131
+ # Download the packages
132
+ # download_packages(packages_to_download, download_folder)
133
+
134
+ # Install packages from local files
135
+ # install_package_from_local_file('torch', folder='packages')
136
+ # install_package_from_local_file('packages/torch/torchvision-0.16.0-cp38-cp38-manylinux1_x86_64.whl', folder='packages/torch')
137
+ # install_package_from_local_file('packages/torch/torchaudio-2.1.0-cp38-cp38-manylinux1_x86_64.whl', folder='packages/torch')
138
+ # install_package_from_local_file('scikit-learn', folder='packages')
139
+ # install_package_from_local_file('open3d', folder='packages')
140
+ install_package_from_local_file('easydict', folder='packages')
141
+ install_package_from_local_file('setuptools', folder='packages')
142
+ # download_packages(['scikit-learn'], folder='packages/scikit-learn')
143
+ # download_packages(['open3d'], folder='packages/open3d')
144
+ # download_packages(['easydict'], folder='packages/easydict')
145
+
146
+ pc_util_path = os.path.join(os.getcwd(), 'pc_util')
147
+ st.write(f"The path to pc_util is {pc_util_path}")
148
+ if os.path.isdir(pc_util_path):
149
+ os.chdir(pc_util_path)
150
+ st.write(f"Installing pc_util from {pc_util_path}")
151
+ subprocess.check_call([sys.executable, "setup.py", "install"])
152
+ st.write("pc_util installed successfully")
153
+ os.chdir("..")
154
+ st.write(f"Current directory is {os.getcwd()}")
155
+ else:
156
+ st.write(f"Directory {pc_util_path} does not exist")
157
+
158
+ setup_cuda_environment()
159
+
160
+ def setup_cuda_environment():
161
+ cuda_home = '/usr/local/cuda/'
162
+ if not os.path.exists(cuda_home):
163
+ raise EnvironmentError(f"CUDA_HOME directory {cuda_home} does not exist. Please install CUDA and set CUDA_HOME environment variable.")
164
+ os.environ['CUDA_HOME'] = cuda_home
165
+ os.environ['PATH'] = f"{cuda_home}/bin:{os.environ['PATH']}"
166
+ os.environ['LD_LIBRARY_PATH'] = f"{cuda_home}/lib64:{os.environ.get('LD_LIBRARY_PATH', '')}"
167
+ print(f"CUDA env setup: {cuda_home}")
168
+
169
+ from pathlib import Path
170
+ def save_submission(submission, path):
171
+ """
172
+ Saves the submission to a specified path.
173
+
174
+ Parameters:
175
+ submission (List[Dict[]]): The submission to save.
176
+ path (str): The path to save the submission to.
177
+ """
178
+ sub = pd.DataFrame(submission, columns=["__key__", "wf_vertices", "wf_edges"])
179
+ sub.to_parquet(path)
180
+ print(f"Submission saved to {path}")
181
+
182
+ def main():
183
+ st.title("Hugging Face Space Prediction App")
184
+
185
+ # Setting up environment
186
+ st.write("Setting up the environment...")
187
+ # setup_environment()
188
+ try:
189
+ setup_environment()
190
+ except Exception as e:
191
+ st.error(f"Env Setup failed: {e}")
192
+ return
193
+
194
+ usr_local_contents = os.listdir('/usr/local')
195
+ # print("Items under /usr/local:")
196
+ for item in usr_local_contents:
197
+ st.write(item)
198
+
199
+ # Print CUDA path
200
+ cuda_home = os.environ.get('CUDA_HOME', 'CUDA_HOME is not set')
201
+ st.write(f"CUDA_HOME: {cuda_home}")
202
+ st.write(f"PATH: {os.environ.get('PATH', 'PATH is not set')}")
203
+ st.write(f"LD_LIBRARY_PATH: {os.environ.get('LD_LIBRARY_PATH', 'LD_LIBRARY_PATH is not set')}")
204
+
205
+ # export PATH=$PATH:/usr/local/cuda/bin
206
+ # export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
207
+ # export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/cuda/lib64
208
+
209
+ from handcrafted_solution import predict
210
+ st.write("Loading dataset...")
211
+
212
+ params = hoho.get_params()
213
+ dataset = hoho.get_dataset(decode=None, split='all', dataset_type='webdataset')
214
+
215
+ st.write('Running predictions...')
216
+ solution = []
217
+ from concurrent.futures import ProcessPoolExecutor
218
+ with ProcessPoolExecutor(max_workers=8) as pool:
219
+ results = []
220
+ for i, sample in enumerate(tqdm(dataset)):
221
+ results.append(pool.submit(predict, sample, visualize=False))
222
+
223
+ for i, result in enumerate(tqdm(results)):
224
+ key, pred_vertices, pred_edges = result.result()
225
+ solution.append({
226
+ '__key__': key,
227
+ 'wf_vertices': pred_vertices.tolist(),
228
+ 'wf_edges': pred_edges
229
+ })
230
+ if i % 100 == 0:
231
+ # Incrementally save the results in case we run out of time
232
+ st.write(f"Processed {i} samples")
233
+
234
+ st.write('Saving results...')
235
+ save_submission(solution, Path(params['output_path']) / "submission.parquet")
236
+ st.write("Done!")
237
+
238
+ if __name__ == "__main__":
239
+ main()
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ webdataset
2
+ opencv-python
3
+ torchvision
4
+ pycolmap
5
+ torch
6
+ kornia>=0.7.1
7
+ matplotlib
8
+ Pillow
9
+ scipy
10
+ plotly
11
+ timm
12
+ open3d
13
+ plyfile
14
+ shapely
15
+ scikit-spatial
16
+ scikit-learn
17
+ numpy
18
+ git+https://hf.co/usm3d/tools.git
19
+ trimesh
20
+ ninja
21
+ transformers