awacke1 commited on
Commit
61aa0e4
·
verified ·
1 Parent(s): 7a98c79

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -0
app.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os, base64, shutil, random
3
+ from pathlib import Path
4
+
5
+ @st.cache_data
6
+ def load_aframe_and_extras():
7
+ return """
8
+ <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
9
+ <script src="https://unpkg.com/[email protected]/dist/aframe-event-set-component.min.js"></script>
10
+ <script>
11
+ AFRAME.registerComponent('draggable', {
12
+ init: function () {
13
+ this.el.setAttribute('class', 'raycastable');
14
+ this.el.setAttribute('cursor-listener', '');
15
+ this.dragHandler = this.dragMove.bind(this);
16
+ this.el.sceneEl.addEventListener('mousemove', this.dragHandler);
17
+ this.el.addEventListener('mousedown', this.onDragStart.bind(this));
18
+ this.el.addEventListener('mouseup', this.onDragEnd.bind(this));
19
+ this.camera = document.querySelector('[camera]');
20
+ },
21
+ remove: function () {
22
+ this.el.removeAttribute('cursor-listener');
23
+ this.el.sceneEl.removeEventListener('mousemove', this.dragHandler);
24
+ },
25
+ onDragStart: function (evt) {
26
+ this.isDragging = true;
27
+ this.el.emit('dragstart');
28
+ },
29
+ onDragEnd: function (evt) {
30
+ this.isDragging = false;
31
+ this.el.emit('dragend');
32
+ },
33
+ dragMove: function (evt) {
34
+ if (!this.isDragging) return;
35
+ var camera = this.camera;
36
+ var vector = new THREE.Vector3(evt.clientX / window.innerWidth * 2 - 1, -(evt.clientY / window.innerHeight) * 2 + 1, 0.5);
37
+ vector.unproject(camera);
38
+ var dir = vector.sub(camera.position).normalize();
39
+ var distance = -camera.position.y / dir.y;
40
+ var pos = camera.position.clone().add(dir.multiplyScalar(distance));
41
+ this.el.setAttribute('position', pos);
42
+ }
43
+ });
44
+ AFRAME.registerComponent('bouncing', {
45
+ schema: {
46
+ speed: {type: 'vec3', default: {x: 0.1, y: 0.1, z: 0.1}},
47
+ dist: {type: 'vec3', default: {x: 0.5, y: 0.5, z: 0.5}}
48
+ },
49
+ init: function () {
50
+ this.originalPos = this.el.getAttribute('position');
51
+ this.dir = {x: 1, y: 1, z: 1};
52
+ },
53
+ tick: function (time, timeDelta) {
54
+ var currentPos = this.el.getAttribute('position');
55
+ var speed = this.data.speed;
56
+ var dist = this.data.dist;
57
+ ['x', 'y', 'z'].forEach(axis => {
58
+ currentPos[axis] += speed[axis] * this.dir[axis] * (timeDelta / 1000);
59
+ if (Math.abs(currentPos[axis] - this.originalPos[axis]) > dist[axis]) {
60
+ this.dir[axis] *= -1;
61
+ }
62
+ });
63
+ this.el.setAttribute('position', currentPos);
64
+ }
65
+ });
66
+ AFRAME.registerComponent('moving-light', {
67
+ schema: {
68
+ color: {type: 'color', default: '#FFF'},
69
+ speed: {type: 'vec3', default: {x: 0.1, y: 0.1, z: 0.1}},
70
+ bounds: {type: 'vec3', default: {x: 5, y: 5, z: 5}}
71
+ },
72
+ init: function () {
73
+ this.dir = {x: 1, y: 1, z: 1};
74
+ this.light = document.createElement('a-light');
75
+ this.light.setAttribute('type', 'point');
76
+ this.light.setAttribute('color', this.data.color);
77
+ this.light.setAttribute('intensity', '0.75');
78
+ this.el.appendChild(this.light);
79
+ },
80
+ tick: function (time, timeDelta) {
81
+ var currentPos = this.el.getAttribute('position');
82
+ var speed = this.data.speed;
83
+ var bounds = this.data.bounds;
84
+ ['x', 'y', 'z'].forEach(axis => {
85
+ currentPos[axis] += speed[axis] * this.dir[axis] * (timeDelta / 1000);
86
+ if (Math.abs(currentPos[axis]) > bounds[axis]) {
87
+ this.dir[axis] *= -1;
88
+ }
89
+ });
90
+ this.el.setAttribute('position', currentPos);
91
+ }
92
+ });
93
+ function moveCamera(direction) {
94
+ var camera = document.querySelector('[camera]');
95
+ var rig = document.querySelector('#rig');
96
+ var pos = rig.getAttribute('position');
97
+ var rot = rig.getAttribute('rotation');
98
+ var speed = 0.5;
99
+ var rotationSpeed = 5;
100
+ switch(direction) {
101
+ case 'up': pos.z -= speed; break;
102
+ case 'down': pos.z += speed; break;
103
+ case 'left': pos.x -= speed; break;
104
+ case 'right': pos.x += speed; break;
105
+ case 'rotateLeft': rot.y += rotationSpeed; break;
106
+ case 'rotateRight': rot.y -= rotationSpeed; break;
107
+ case 'reset': pos = {x: 0, y: 10, z: 0}; rot = {x: -90, y: 0, z: 0}; break;
108
+ case 'ground': pos = {x: 0, y: 1.6, z: 0}; rot = {x: 0, y: 0, z: 0}; break;
109
+ }
110
+ rig.setAttribute('position', pos);
111
+ rig.setAttribute('rotation', rot);
112
+ }
113
+ document.addEventListener('keydown', function(event) {
114
+ switch(event.key.toLowerCase()) {
115
+ case 'q': moveCamera('rotateLeft'); break;
116
+ case 'e': moveCamera('rotateRight'); break;
117
+ case 'z': moveCamera('reset'); break;
118
+ case 'c': moveCamera('ground'); break;
119
+ }
120
+ });
121
+ </script>
122
+ """
123
+
124
+ def create_aframe_entity(file_stem, file_type, position):
125
+ rotation = f"0 {random.uniform(0, 360)} 0"
126
+ bounce_speed = f"{random.uniform(0.05, 0.1)} {random.uniform(0.05, 0.1)} {random.uniform(0.05, 0.1)}"
127
+ bounce_dist = f"0.1 0.1 0.1"
128
+ if file_type == 'obj':
129
+ return f'<a-entity position="{position}" rotation="{rotation}" scale="0.5 0.5 0.5" obj-model="obj: #{file_stem}" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-entity>'
130
+ elif file_type == 'glb':
131
+ return f'<a-entity position="{position}" rotation="{rotation}" scale="0.5 0.5 0.5" gltf-model="#{file_stem}" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-entity>'
132
+ elif file_type in ['webp', 'png']:
133
+ return f'<a-image position="{position}" rotation="-90 0 0" src="#{file_stem}" width="0.5" height="0.5" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-image>'
134
+ elif file_type == 'mp4':
135
+ return f'<a-video position="{position}" rotation="-90 0 0" src="#{file_stem}" width="0.5" height="0.5" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-video>'
136
+ return ''
137
+
138
+ @st.cache_data
139
+ def encode_file(file_path):
140
+ with open(file_path, "rb") as file:
141
+ return base64.b64encode(file.read()).decode()
142
+
143
+ @st.cache_data
144
+ def generate_tilemap(files, directory, grid_width, grid_height, max_unique_models=5):
145
+ assets = "<a-assets>"
146
+ entities = ""
147
+ tile_size = 1
148
+ start_x = -(grid_width * tile_size) / 2
149
+ start_z = -(grid_height * tile_size) / 2
150
+ unique_files = random.sample(files, min(len(files), max_unique_models))
151
+ encoded_files = {}
152
+ for file in unique_files:
153
+ file_path = os.path.join(directory, file)
154
+ file_type = file.split('.')[-1]
155
+ encoded_file = encode_file(file_path)
156
+ encoded_files[file] = encoded_file
157
+ if file_type in ['obj', 'glb']:
158
+ assets += f'<a-asset-item id="{Path(file).stem}" src="data:application/octet-stream;base64,{encoded_file}"></a-asset-item>'
159
+ elif file_type in ['webp', 'png', 'mp4']:
160
+ mime_type = f"image/{file_type}" if file_type in ['webp', 'png'] else "video/mp4"
161
+ assets += f'<{file_type} id="{Path(file).stem}" src="data:{mime_type};base64,{encoded_file}"></{file_type}>'
162
+ for i in range(grid_width):
163
+ for j in range(grid_height):
164
+ x = start_x + (i * tile_size)
165
+ z = start_z + (j * tile_size)
166
+ position = f"{x} 0 {z}"
167
+ if unique_files:
168
+ file = random.choice(unique_files)
169
+ file_type = file.split('.')[-1]
170
+ entities += create_aframe_entity(Path(file).stem, file_type, position)
171
+ assets += "</a-assets>"
172
+ return assets, entities
173
+
174
+ def main():
175
+ st.set_page_config(layout="wide")
176
+ with st.sidebar:
177
+ st.markdown("### 🤖 3D AI Using Claude 3.5 Sonnet for AI Pair Programming")
178
+ st.markdown("[Open 3D Animation Toolkit](https://huggingface.co/spaces/awacke1/3d_animation_toolkit)", unsafe_allow_html=True)
179
+ st.markdown("### ⬆️ Upload")
180
+ uploaded_files = st.file_uploader("Add files:", accept_multiple_files=True, key="file_uploader")
181
+ st.markdown("### 🎮 Camera Controls")
182
+ col1, col2, col3 = st.columns(3)
183
+ with col1:
184
+ st.button("⬅️", on_click=lambda: st.session_state.update({'camera_move': 'left'}))
185
+ st.button("🔄↺", on_click=lambda: st.session_state.update({'camera_move': 'rotateLeft'}))
186
+ st.button("🔝", on_click=lambda: st.session_state.update({'camera_move': 'reset'}))
187
+ with col2:
188
+ st.button("⬆️", on_click=lambda: st.session_state.update({'camera_move': 'up'}))
189
+ st.button("🔄↻", on_click=lambda: st.session_state.update({'camera_move': 'rotateRight'}))
190
+ st.button("👀", on_click=lambda: st.session_state.update({'camera_move': 'ground'}))
191
+ with col3:
192
+ st.button("➡️", on_click=lambda: st.session_state.update({'camera_move': 'right'}))
193
+ st.button("⬇️", on_click=lambda: st.session_state.update({'camera_move': 'down'}))
194
+ st.markdown("### 🗺️ Grid Size")
195
+ grid_width = st.slider("Grid Width", 1, 8, 8)
196
+ grid_height = st.slider("Grid Height", 1, 5, 5)
197
+ st.markdown("### ℹ️ Instructions")
198
+ st.write("- WASD: Move camera\n- Q/E: Rotate camera left/right\n- Z: Reset camera to top view\n- C: Move camera to ground level\n- Click and drag to move objects\n- Mouse wheel to zoom\n- Right-click and drag to rotate view")
199
+ st.markdown("### 📁 Directory")
200
+ directory = st.text_input("Enter path:", ".", key="directory_input")
201
+ if not os.path.isdir(directory):
202
+ st.sidebar.error("Invalid directory path")
203
+ return
204
+ file_types = ['obj', 'glb', 'webp', 'png', 'mp4']
205
+ if uploaded_files:
206
+ for uploaded_file in uploaded_files:
207
+ file_extension = Path(uploaded_file.name).suffix.lower()[1:]
208
+ if file_extension in file_types:
209
+ with open(os.path.join(directory, uploaded_file.name), "wb") as f:
210
+ shutil.copyfileobj(uploaded_file, f)
211
+ st.sidebar.success(f"Uploaded: {uploaded_file.name}")
212
+ else:
213
+ st.sidebar.warning(f"Skipped unsupported file: {uploaded_file.name}")
214
+ files = [f for f in os.listdir(directory) if f.split('.')[-1] in file_types]
215
+ aframe_scene = f"""
216
+ <a-scene embedded style="height: 600px; width: 100%;">
217
+ <a-entity id="rig" position="0 {max(grid_width, grid_height)} 0" rotation="-90 0 0">
218
+ <a-camera fov="60" look-controls wasd-controls cursor="rayOrigin: mouse" raycaster="objects: .raycastable"></a-camera>
219
+ </a-entity>
220
+ <a-sky color="#87CEEB"></a-sky>
221
+ <a-entity moving-light="color: #FFD700; speed: 0.07 0.05 0.06; bounds: 4 3 4" position="2 2 -2"></a-entity>
222
+ <a-entity moving-light="color: #FF6347; speed: 0.06 0.08 0.05; bounds: 4 3 4" position="-2 1 2"></a-entity>
223
+ <a-entity moving-light="color: #00CED1; speed: 0.05 0.06 0.07; bounds: 4 3 4" position="0 3 0"></a-entity>
224
+ """
225
+ assets, entities = generate_tilemap(files, directory, grid_width, grid_height, max_unique_models=5)
226
+ aframe_scene += assets + entities + "</a-scene>"
227
+ camera_move = st.session_state.get('camera_move', None)
228
+ if camera_move:
229
+ aframe_scene += f"<script>moveCamera('{camera_move}');</script>"
230
+ st.session_state.pop('camera_move')
231
+ st.components.v1.html(load_aframe_and_extras() + aframe_scene, height=600)
232
+
233
+ if __name__ == "__main__":
234
+ main()