awacke1 commited on
Commit
cb46809
·
verified ·
1 Parent(s): 755bd8f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -0
app.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import base64
4
+ from pathlib import Path
5
+ import shutil
6
+ import random
7
+
8
+ def load_aframe_and_extras():
9
+ return """
10
+ <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
11
+ <script src="https://unpkg.com/aframe-event-set-component@5.0.0/dist/aframe-event-set-component.min.js"></script>
12
+ <script>
13
+ AFRAME.registerComponent('draggable', {
14
+ init: function () {
15
+ this.el.setAttribute('class', 'raycastable');
16
+ this.el.setAttribute('cursor-listener', '');
17
+ this.dragHandler = this.dragMove.bind(this);
18
+ this.el.sceneEl.addEventListener('mousemove', this.dragHandler);
19
+ this.el.addEventListener('mousedown', this.onDragStart.bind(this));
20
+ this.el.addEventListener('mouseup', this.onDragEnd.bind(this));
21
+ this.camera = document.querySelector('[camera]');
22
+ },
23
+ remove: function () {
24
+ this.el.removeAttribute('cursor-listener');
25
+ this.el.sceneEl.removeEventListener('mousemove', this.dragHandler);
26
+ },
27
+ onDragStart: function (evt) {
28
+ this.isDragging = true;
29
+ this.el.emit('dragstart');
30
+ },
31
+ onDragEnd: function (evt) {
32
+ this.isDragging = false;
33
+ this.el.emit('dragend');
34
+ },
35
+ dragMove: function (evt) {
36
+ if (!this.isDragging) return;
37
+ var camera = this.camera;
38
+ var vector = new THREE.Vector3(evt.clientX / window.innerWidth * 2 - 1, -(evt.clientY / window.innerHeight) * 2 + 1, 0.5);
39
+ vector.unproject(camera);
40
+ var dir = vector.sub(camera.position).normalize();
41
+ var distance = -camera.position.y / dir.y;
42
+ var pos = camera.position.clone().add(dir.multiplyScalar(distance));
43
+ this.el.setAttribute('position', pos);
44
+ }
45
+ });
46
+
47
+ AFRAME.registerComponent('bouncing', {
48
+ schema: {
49
+ speed: {type: 'vec3', default: {x: 0.1, y: 0.1, z: 0.1}},
50
+ dist: {type: 'vec3', default: {x: 2, y: 2, z: 2}}
51
+ },
52
+ init: function () {
53
+ this.originalPos = this.el.getAttribute('position');
54
+ this.dir = {x: 1, y: 1, z: 1};
55
+ },
56
+ tick: function (time, timeDelta) {
57
+ var currentPos = this.el.getAttribute('position');
58
+ var speed = this.data.speed;
59
+ var dist = this.data.dist;
60
+
61
+ ['x', 'y', 'z'].forEach(axis => {
62
+ currentPos[axis] += speed[axis] * this.dir[axis] * (timeDelta / 1000);
63
+ if (Math.abs(currentPos[axis] - this.originalPos[axis]) > dist[axis]) {
64
+ this.dir[axis] *= -1;
65
+ }
66
+ });
67
+
68
+ this.el.setAttribute('position', currentPos);
69
+ }
70
+ });
71
+
72
+ function moveCamera(direction) {
73
+ var camera = document.querySelector('[camera]');
74
+ var pos = camera.getAttribute('position');
75
+ var rot = camera.getAttribute('rotation');
76
+ var speed = 0.5;
77
+
78
+ switch(direction) {
79
+ case 'up':
80
+ pos.y += speed;
81
+ break;
82
+ case 'down':
83
+ pos.y -= speed;
84
+ break;
85
+ case 'left':
86
+ pos.x -= speed;
87
+ break;
88
+ case 'right':
89
+ pos.x += speed;
90
+ break;
91
+ case 'center':
92
+ pos = {x: 0, y: 2, z: 2};
93
+ rot = {x: -45, y: 0, z: 0};
94
+ break;
95
+ }
96
+
97
+ camera.setAttribute('position', pos);
98
+ if (direction === 'center') {
99
+ camera.setAttribute('rotation', rot);
100
+ }
101
+ }
102
+ </script>
103
+ """
104
+
105
+ def create_aframe_entity(file_path, file_type, position):
106
+ rotation = f"{random.uniform(0, 360)} {random.uniform(0, 360)} {random.uniform(0, 360)}"
107
+ bounce_speed = f"{random.uniform(0.05, 0.2)} {random.uniform(0.05, 0.2)} {random.uniform(0.05, 0.2)}"
108
+ bounce_dist = f"{random.uniform(0.5, 1.5)} {random.uniform(0.5, 1.5)} {random.uniform(0.5, 1.5)}"
109
+
110
+ if file_type == 'obj':
111
+ return f'<a-entity position="{position}" rotation="{rotation}" obj-model="obj: #{Path(file_path).stem}" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-entity>'
112
+ elif file_type == 'glb':
113
+ return f'<a-entity position="{position}" rotation="{rotation}" gltf-model="#{Path(file_path).stem}" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-entity>'
114
+ elif file_type in ['webp', 'png']:
115
+ return f'<a-image position="{position}" rotation="{rotation}" src="#{Path(file_path).stem}" width="1" height="1" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-image>'
116
+ elif file_type == 'mp4':
117
+ return f'<a-video position="{position}" rotation="{rotation}" src="#{Path(file_path).stem}" width="1" height="1" class="raycastable" draggable bouncing="speed: {bounce_speed}; dist: {bounce_dist}"></a-video>'
118
+ return ''
119
+
120
+ def encode_file(file_path):
121
+ with open(file_path, "rb") as file:
122
+ return base64.b64encode(file.read()).decode()
123
+
124
+ def main():
125
+ st.set_page_config(layout="wide")
126
+
127
+ with st.sidebar:
128
+ st.title("3D File Viewer 🌐")
129
+
130
+ st.markdown("### 🎨 Create Assets")
131
+ st.markdown("[Open 3D Animation Toolkit](https://huggingface.co/spaces/awacke1/3d_animation_toolkit)", unsafe_allow_html=True)
132
+
133
+ st.markdown("### 📁 Directory")
134
+ directory = st.text_input("Enter path:", ".", key="directory_input")
135
+
136
+ st.markdown("### ⬆️ Upload")
137
+ uploaded_files = st.file_uploader("Add files:", accept_multiple_files=True, key="file_uploader")
138
+
139
+ st.markdown("### 🎮 Camera Controls")
140
+ col1, col2, col3 = st.columns(3)
141
+ with col1:
142
+ st.button("⬅️", on_click=lambda: st.session_state.update({'camera_move': 'left'}))
143
+ with col2:
144
+ st.button("⬆️", on_click=lambda: st.session_state.update({'camera_move': 'up'}))
145
+ st.button("🔄", on_click=lambda: st.session_state.update({'camera_move': 'center'}))
146
+ st.button("⬇️", on_click=lambda: st.session_state.update({'camera_move': 'down'}))
147
+ with col3:
148
+ st.button("➡️", on_click=lambda: st.session_state.update({'camera_move': 'right'}))
149
+
150
+ st.markdown("### ℹ️ Instructions")
151
+ st.write("- Click and drag to move objects")
152
+ st.write("- Use camera controls to navigate")
153
+ st.write("- Objects bounce automatically")
154
+
155
+ if not os.path.isdir(directory):
156
+ st.sidebar.error("Invalid directory path")
157
+ return
158
+
159
+ file_types = ['obj', 'glb', 'webp', 'png', 'mp4']
160
+
161
+ if uploaded_files:
162
+ for uploaded_file in uploaded_files:
163
+ file_extension = Path(uploaded_file.name).suffix.lower()[1:]
164
+ if file_extension in file_types:
165
+ with open(os.path.join(directory, uploaded_file.name), "wb") as f:
166
+ shutil.copyfileobj(uploaded_file, f)
167
+ st.sidebar.success(f"Uploaded: {uploaded_file.name}")
168
+ else:
169
+ st.sidebar.warning(f"Skipped unsupported file: {uploaded_file.name}")
170
+
171
+ files = [f for f in os.listdir(directory) if f.split('.')[-1] in file_types]
172
+
173
+ aframe_scene = """
174
+ <a-scene embedded style="height: 600px; width: 100%;">
175
+ <a-entity id="rig" position="0 2 2" rotation="-45 0 0">
176
+ <a-entity camera look-controls wasd-controls cursor="rayOrigin: mouse" raycaster="objects: .raycastable"></a-entity>
177
+ </a-entity>
178
+ """
179
+
180
+ assets = "<a-assets>"
181
+ entities = ""
182
+
183
+ for i, file in enumerate(files):
184
+ file_path = os.path.join(directory, file)
185
+ file_type = file.split('.')[-1]
186
+ encoded_file = encode_file(file_path)
187
+
188
+ if file_type in ['obj', 'glb']:
189
+ assets += f'<a-asset-item id="{Path(file).stem}" src="data:application/octet-stream;base64,{encoded_file}"></a-asset-item>'
190
+ elif file_type in ['webp', 'png', 'mp4']:
191
+ mime_type = f"image/{file_type}" if file_type in ['webp', 'png'] else "video/mp4"
192
+ assets += f'<{file_type} id="{Path(file).stem}" src="data:{mime_type};base64,{encoded_file}"></{file_type}>'
193
+
194
+ position = f"{random.uniform(-3, 3)} {random.uniform(0, 3)} {random.uniform(-3, 3)}"
195
+ entities += create_aframe_entity(file_path, file_type, position)
196
+
197
+ assets += "</a-assets>"
198
+ aframe_scene += assets + entities + "</a-scene>"
199
+
200
+ camera_move = st.session_state.get('camera_move', None)
201
+ if camera_move:
202
+ aframe_scene += f"<script>moveCamera('{camera_move}');</script>"
203
+ st.session_state.pop('camera_move')
204
+
205
+ st.components.v1.html(load_aframe_and_extras() + aframe_scene, height=600)
206
+
207
+ if __name__ == "__main__":
208
+ main()