awacke1 commited on
Commit
cc49b29
·
verified ·
1 Parent(s): 6dcce46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +441 -349
app.py CHANGED
@@ -1,349 +1,441 @@
1
- import streamlit as st
2
- import streamlit.components.v1 as components
3
-
4
- # --------------------------
5
- # Mermaid Renderer Function
6
- # --------------------------
7
- def render_mermaid(mermaid_code, height=300):
8
- """Render a mermaid diagram using an HTML snippet in a Streamlit component."""
9
- html_code = f"""
10
- <html>
11
- <head>
12
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"></script>
13
- <style>
14
- body {{
15
- background-color: white;
16
- font-family: sans-serif;
17
- }}
18
- </style>
19
- </head>
20
- <body>
21
- <div class="mermaid">
22
- {mermaid_code}
23
- </div>
24
- <script>
25
- mermaid.initialize({{startOnLoad:true}});
26
- </script>
27
- </body>
28
- </html>
29
- """
30
- components.html(html_code, height=height)
31
-
32
- # --------------------------
33
- # Markdown Outlines for Each Area
34
- # --------------------------
35
- markdown_areas = {
36
- "1. 👥 Leadership Management Collaboration LeCo": r'''
37
- 1. 👥 Leadership Management Collaboration LeCo
38
- ''',
39
- "2. 🔒 Security Compliance Reliability SeCo": r'''
40
- 2. 🔒 Security Compliance Reliability SeCo
41
- ''',
42
- "3. 📊 Data Engineering Analytics Data Governance DaEn": r'''
43
- 3. 📊 Data Engineering Analytics Data Governance DaEn
44
- ''',
45
- "4. 📢 Community OpenSource Communication CoOS": r'''
46
- 4. 📢 Community OpenSource Communication CoOS
47
- ''',
48
- "5. 📱 FullStack UI Mobile Product Development FuMo": r'''
49
- 5. 📱 FullStack UI Mobile Product Development FuMo
50
- ''',
51
- "6. 💻 Software Cloud MLOps Infrastructure SCMI": r'''
52
- 6. 💻 Software Cloud MLOps Infrastructure SCMI
53
- ''',
54
- "7. 🤖 Machine Learning AI Model Development MLAI": r'''
55
- 7. 🤖 Machine Learning AI Model Development MLAI
56
- ''',
57
- "8. 🔧 Systems Infrastructure LowLevel Engineering SyIn": r'''
58
- 8. 🔧 Systems Infrastructure LowLevel Engineering SyIn
59
- ''',
60
- "9. 🎯 Specialized Domains Emerging Technologies SpDo": r'''
61
- 9. 🎯 Specialized Domains Emerging Technologies SpDo
62
- '''
63
- }
64
-
65
- # --------------------------
66
- # Mermaid Diagrams for Each Area
67
- # --------------------------
68
- mermaid_areas = {
69
- "1. 👥 Leadership Management Collaboration LeCo": r'''
70
- graph LR
71
- LeCo["🗼LeCo👥 Leadership and Collaboration"]
72
- LeCo -->|🚀 Guides| LeCo1a["1. 🚀 Strategic and Cross-Functional Leadership - Global strategy, team coordination and vendor management"]
73
- LeCo -->|🤝 Supports| LeCo1b["2. 🤝 Team Building and Agile Collaboration - Coaching, agile processes and stakeholder management"]
74
- LeCo -->|💡 Innovates| LeCo1c["3. 💡 Domain Expertise and Innovation - Deep AI knowledge and product strategy"]
75
- ''',
76
- "2. 🔒 Security Compliance Reliability SeCo": r'''
77
- graph LR
78
- SeCo["👓SeCo🔒 Security and Compliance"]
79
- SeCo -->|🛡️ Protects| SeCo1["1. 🛡️ Security Operations and Incident Response - Incident management, pen testing and vulnerability assessment"]
80
- SeCo -->|✅ Regulates| SeCo2["2. ✅ Compliance and Governance - Data quality, compliance policies and IAM"]
81
- SeCo -->|🔒 Secures| SeCo3["3. 🔒 System Hardening and Automation - Secure HPC, ML, Python, Bash automation and cost optimization"]
82
- ''',
83
- "3. 📊 Data Engineering Analytics Data Governance DaEn": r'''
84
- graph LR
85
- DaEn["🪑DaEn📊 Data Engineering"]
86
- DaEn -->|💧 Processes| DaEn1["1. 💧 Data Processing and Ingestion - Multi-modal data, event handling and ETL"]
87
- DaEn -->|📊 Analyzes| DaEn2["2. 📊 Analytics, Forecasting and Visualization - BI, dashboards and forecasting"]
88
- DaEn -->|📝 Governs| DaEn3["3. 📝 Data Governance and Quality - Modeling, warehousing and stakeholder communications"]
89
- ''',
90
- "4. 📢 Community OpenSource Communication CoOS": r'''
91
- graph LR
92
- CoOS["🪟CoOS📢 Community OpenSource"]
93
- CoOS -->|📚 Documents| CoOS1["1. 📚 Technical Documentation and Demos - Code examples, demos and notebooks"]
94
- CoOS -->|💬 Engages| CoOS2["2. 💬 Community Engagement and Collaboration - Public speaking, social media and collaborations"]
95
- ''',
96
- "5. 📱 FullStack UI Mobile Product Development FuMo": r'''
97
- graph LR
98
- FuMo["✋FuMo📱 FullStack UI Mobile"]
99
- FuMo -->|📱 Develops| FuMo1["1. 📱 Mobile and Web App Development - Full stack development, CI/CD and API design"]
100
- FuMo -->|🎨 Designs| FuMo2["2. 🎨 UI, UX and Frontend Integration - React, Next.js, TypeScript and intuitive design"]
101
- FuMo -->|🔌 Connects| FuMo3["3. 🔌 Backend and Cross-Platform Tools - Python, Node, cloud microservices and ML bridging"]
102
- ''',
103
- "6. 💻 Software Cloud MLOps Infrastructure SCMI": r'''
104
- graph LR
105
- SoCM["🎲SoCM💻 Software Cloud MLOps"]
106
- SoCM -->|🛠️ Optimizes| SCMI1["1. 🛠️ Developer Tooling and Observability - Full stack dev, debugging and SRE practices"]
107
- SoCM -->|🤖 Automates| SCMI2["2. 🤖 ML Frameworks and Automation - Python APIs, PyTorch, Keras and Ray, Horovod"]
108
- SoCM -->|🔄 Pipelines| SCMI3["3. 🔄 Data Pipelines and Processing - Spark, Airflow and ETL pipelines"]
109
- SoCM -->|☁️ Deploys| SCMI4["4. ☁️ Cloud and Infrastructure Provisioning - Kubernetes, Docker, Terraform and cloud integration"]
110
- ''',
111
- "7. 🤖 Machine Learning AI Model Development MLAI": r'''
112
- graph LR
113
- AIML["☁️AIML🤖 AI Machine Learning"]
114
- AIML -->|🏛️ Structures| MLAI1["1. 🏛️ Large-Scale Architectures and Retrieval - Transformers, RAG and vector DBs"]
115
- AIML -->|⚗️ Experiments| MLAI2["2. ⚗️ Experimentation and Distributed Training - RL, quantization and ablation studies"]
116
- AIML -->|📡 Deploys| MLAI3["3. 📡 Application and API Development - Agentic AI, LLM inference and microservices"]
117
- AIML -->|📈 Optimizes| MLAI4["4. 📈 Optimization and Monitoring - Performance tuning, scaling and reliability"]
118
- ''',
119
- "8. 🔧 Systems Infrastructure LowLevel Engineering SyIn": r'''
120
- graph LR
121
- SyIn["🚪SyIn🔧 Systems Infrastructure"]
122
- SyIn -->|🐧 Integrates| SyIn1["1. 🐧 Hardware and OS Integration - Linux, embedded, C, C++"]
123
- SyIn -->|⚙️ Tunes| SyIn2["2. ⚙️ Performance and Tuning - Cross-layer tuning, throughput and load balancing"]
124
- SyIn -->|🤖 Enhances| SyIn3["3. 🤖 Advanced ML and Automation - Cross-team innovation, observability and ServiceNow"]
125
- SyIn -->|🚀 Scales| SyIn4["4. 🚀 Distributed and HPC Deployment - Data center HPC, ML, GPU orchestration and multi-GPU pipelines"]
126
- ''',
127
- "9. 🎯 Specialized Domains Emerging Technologies SpDo": r'''
128
- graph LR
129
- SpDo["🐱SpDo🎯 Specialized Domains"]
130
- SpDo -->|🎥 Visualizes| SpDo1["1. 🎥 Advanced CV and 3D Graphics - Neural rendering, reconstruction and graphics engines"]
131
- SpDo -->|🚗 Automates| SpDo2["2. 🚗 Robotics and Autonomous Systems - Autonomous vehicles, sensor fusion and path planning"]
132
- SpDo -->|💻 Computes| SpDo3["3. 💻 HPC and Hardware Integration - GPU, SoC modeling, HPC networking and prototyping"]
133
- SpDo -->|🔢 Quantizes| SpDo4["4. 🔢 AI Quantization and Inference - Quantization, in-browser inference and neural sparse models"]
134
- '''
135
- }
136
-
137
- # --------------------------
138
- # Markdown Sections
139
- # --------------------------
140
-
141
- md_combined_outline = r'''
142
- # 📚 Hands On ML App. Dev. with Mixture of Experts and Multiagent Skills and State of Art ML Architecture
143
- 1. 🗼LeCo👥 Leadership and Collaboration : Strategic leadership and team management.
144
- 2. 👓SeCo🔒 Security and Compliance : Security operations, compliance, and system hardening.
145
- 3. 🪑DaEn📊 Data Engineering : Data processing, analytics, and governance.
146
- 4. 🪟CoOS📢 Community OpenSource : Community engagement, documentation, and collaboration.
147
- 5. ✋FuMo📱 FullStack UI Mobile : Mobile and web app development with ML integration.
148
- 6. 🎲SoCM💻 Software Cloud MLOps : Cloud infrastructure, ML frameworks, and automation.
149
- 7. ☁️AIML🤖 AI Machine Learning : Large–scale architectures, distributed training, and inference.
150
- 8. 🚪SyIn🔧 Systems Infrastructure : Hardware, OS, and distributed HPC deployments.
151
- 9. 🐱SpDo🎯 Specialized Domains : Advanced CV, robotics, HPC, and AI quantization.
152
- '''
153
-
154
- md_submodels_outline = r'''
155
- ## 1. 👥 Leadership Management Collaboration LeCo
156
- 1. **🚀 Strategic and Cross-Functional Leadership - Global strategy, team coordination and vendor management**
157
- 2. **🤝 Team Building and Agile Collaboration - Coaching, agile processes and stakeholder management**
158
- 3. **💡 Domain Expertise and Innovation - Deep AI framework knowledge and product strategy**
159
-
160
- ## 2. 🔒 Security Compliance Reliability SeCo
161
- 1. **🛡️ Security Operations and Incident Response - Incident management, pen testing and vulnerability assessment**
162
- 2. **✅ Compliance and Governance - Data quality standards, compliance policies and IAM solutions**
163
- 3. **🔒 System Hardening and Automation - Secure HPC, ML, Python, Bash automation and cost optimization**
164
-
165
- ## 3. 📊 Data Engineering Analytics Data Governance DaEn
166
- 1. **💧 Data Processing and Ingestion - Multi, modal data, event handling and ETL pipelines**
167
- 2. **📊 Analytics, Forecasting and Visualization - BI, dashboards and forecasting**
168
- 3. **📝 Data Governance and Quality - Modeling, warehousing and stakeholder comms**
169
-
170
- ## 4. 📢 Community OpenSource Communication CoOS
171
- 1. **📚 Technical Documentation and Demos - Code examples, demos and notebooks**
172
- 2. **💬 Community Engagement and Collaboration - Public speaking, social media and collabs**
173
-
174
- ## 5. 📱 FullStack UI Mobile Product Development FuMo
175
- 1. **📱 Mobile and Web App Development - Full stack development, CI/CD and API design**
176
- 2. **🎨 UI, UX and Frontend Integration - React, Next.js, TypeScript and intuitive design**
177
- 3. **🔌 Backend and Cross-Platform Tools - Python, Node, cloud microservices and ML bridging**
178
-
179
- ## 6. 💻 Software Cloud MLOps Infrastructure SoCM
180
- 1. **🛠️ Developer Tooling and Observability - Full stack dev, debugging and SRE practices**
181
- 2. **🤖 ML Frameworks and Automation - Python APIs, PyTorch, Keras and Ray, Horovod**
182
- 3. **🔄 Data Pipelines and Processing - Spark, Airflow and ETL pipelines**
183
- 4. **☁️ Cloud and Infrastructure Provisioning - Kubernetes, Docker, Terraform and cloud integration**
184
-
185
- ## 7. 🤖 AI Machine Learning Model Development AIML
186
- 1. **🏛️ Large-Scale Architectures and Retrieval - Transformers, RAG and vector DBs**
187
- 2. **⚗️ Experimentation and Distributed Training - RL, quantization and ablation studies**
188
- 3. **📡 Application and API Development - Agentic AI, LLM inference and microservices**
189
- 4. **📈 Optimization and Monitoring - Performance tuning, scaling and reliability**
190
-
191
- ## 8. 🔧 Systems Infrastructure LowLevel Engineering SyIn
192
- 1. **🐧 Hardware and OS Integration - Linux, embedded, C, C++**
193
- 2. **⚙️ Performance and Tuning - Cross-layer tuning, throughput and load balancing**
194
- 3. **🤖 Advanced ML and Automation - Cross-team innovation, observability and ServiceNow**
195
- 4. **🚀 Distributed and HPC Deployment - Data center HPC, ML, GPU orchestration and multi-GPU pipelines**
196
-
197
- ## 9. 🎯 Specialized Domains Emerging Technologies SpDo
198
- 1. **🎥 Advanced CV and 3D Graphics - Neural rendering, reconstruction and graphics engines**
199
- 2. **🚗 Robotics and Autonomous Systems - Autonomous vehicles, sensor fusion and path planning**
200
- 3. **💻 HPC and Hardware Integration - GPU, SoC modeling, HPC networking and prototyping**
201
- 4. **🔢 AI Quantization and Inference - Quantization, in-browser inference and neural sparse models**
202
- '''
203
-
204
- md_glossary = r'''
205
- # 📖 Glossary
206
- 1. **🔧 Systems Infrastructure SyIn:** Hardware and OS, level operations enabling computing environments.
207
- 2. **💻 Software Cloud MLOps SCMI:** Tools and processes for managing ML workflows and cloud infrastructures.
208
- 3. **🤖 Machine Learning AI MLAI:** Techniques and architectures for developing and deploying AI models.
209
- 4. **📊 Data Engineering DaEn:** Methods for processing, analyzing and governing data.
210
- 5. **🔒 Security and Compliance SeCo:** Practices ensuring system security and adherence to regulations.
211
- 6. **👥 Leadership and Collaboration LeCo:** Strategies for effective team management and cross-functional coordination.
212
- 7. **📱 FullStack UI Mobile FuMo:** End-to-end development of mobile and web interfaces integrating ML.
213
- 8. **🎯 Specialized Domains SpDo:** Focus areas in advanced tech such as computer vision, robotics and HPC.
214
- 9. **📢 Community OpenSource CoOS:** Engagement with open-source communities and technical education.
215
- 10. **HPC:** High Performance Computing; large-scale computational systems and clusters.
216
- 11. **LLM:** Large Language Models; deep learning models for natural language processing.
217
- 12. **MLOps:** Machine Learning Operations; practices for deploying and managing ML systems.
218
- '''
219
-
220
- md_python_libraries = r'''
221
- # 🐍 Python Libraries Guide
222
- 1. **🔥 TensorFlow (tensorflow) -** Deep learning library for research and production.
223
- 2. **🤗 Huggingface Hub (huggingface_hub) -** Platform for sharing and accessing pre-trained models.
224
- 3. **🔄 Transformers (transformers) -** Library for NLP and model inference.
225
- 4. **🔥 Torch (torch) -** PyTorch library for dynamic deep learning.
226
- 5. **🚀 Streamlit (streamlit) -** Rapidly build interactive ML web apps.
227
- 6. **🎙️ Gradio (gradio) -** Create customizable web interfaces for ML models.
228
- 7. **🐼 Pandas (pandas) -** Data manipulation and analysis.
229
- 8. **🔢 NumPy (numpy) -** Numerical computing and array operations.
230
- 9. **💬 LangChain (langchain) -** Framework for building applications with language models.
231
- 10. **🤖 OpenAI (openai) -** API for accessing GPT models and AI services.
232
- 11. **🔑 Azure MSAL (msal) -** Authentication library for Azure services.
233
- 12. **⚙️ Scikit-learn (scikit-learn) -** Machine learning tools for data mining and analysis.
234
- 13. **📈 Matplotlib (matplotlib) -** Plotting library for data visualization.
235
- 14. **🔍 Seaborn (seaborn) -** Statistical data visualization.
236
- 15. **📊 Plotly (plotly) -** Interactive graphing library.
237
- 16. **📚 NLTK (nltk) -** Natural language processing toolkit.
238
- 17. **🧪 SciPy (scipy) -** Scientific and technical computing.
239
- 18. **⚡ FastAPI (fastapi) -** Build fast APIs for ML applications.
240
- 19. **🛠 Dask (dask) -** Parallel computing with task scheduling.
241
- 20. **🔗 Requests (requests) -** HTTP library for Python.
242
- '''
243
-
244
- md_js_libraries = r'''
245
- # 💻 JavaScript Libraries Guide
246
- 1. **🔥 React (react) -** Library for building UI components.
247
- 2. **⚛️ Redux (redux) -** Predictable state container for JavaScript apps.
248
- 3. **🌐 Node.js (node) -** JavaScript runtime for building server-side applications.
249
- 4. **💻 Express (express) -** Web framework for Node.js.
250
- 5. **🔗 D3.js (d3) -** Library for dynamic, interactive data visualizations.
251
- 6. **📊 Chart.js (chart.js) -** Simple yet flexible charting library.
252
- 7. **🛠 Webpack (webpack) -** Module bundler for JavaScript applications.
253
- 8. **⚙️ Babel (babel) -** Transpiler for next-generation JavaScript.
254
- 9. **🚀 Next.js (next) -** React framework for server-side rendering.
255
- 10. **🎨 Tailwind CSS (tailwindcss) -** Utility-first CSS framework for rapid UI development.
256
- 11. **🌀 jQuery (jquery) -** DOM manipulation library.
257
- 12. **🔍 Lodash (lodash) -** Utility library for JavaScript.
258
- 13. **⏰ Moment.js (moment) -** Date library for parsing, validating and formatting dates.
259
- 14. **📡 Axios (axios) -** Promise-based HTTP client.
260
- 15. **💬 Socket.io (socket.io) -** Real-time communication library.
261
- 16. **🖼 Vue.js (vue) -** Progressive framework for building user interfaces.
262
- 17. **🅰️ Angular (angular) -** Platform for building mobile and desktop web applications.
263
- 18. **🔥 Ember.js (ember) -** Framework for creating ambitious web applications.
264
- 19. **📊 Mermaid.js (mermaid) -** Library for generating diagrams and flowcharts.
265
- 20. **🎇 Three.js (three) -** Library for creating 3D graphics in the browser.
266
- '''
267
-
268
- md_picture_mnemonic = r'''
269
- # 🖼 Picture Mnemonic Outline
270
- 1. **🗼 Lighthouse -** Represents #1, a beacon of guidance.
271
- 2. **👓 Eyeglasses -** Symbolizes #2, two lenses for clarity.
272
- 3. **🪑 Stool -** Denotes #3, three legs for stability.
273
- 4. **🪟 Window -** Four panes, representing #4.
274
- 5. **✋ Hand -** Five fingers for #5.
275
- 6. **🎲 Dice -** Six sides symbolizing #6.
276
- 7. **☁️ Cloud -** For #7, light and airy.
277
- 8. **🚪 Gate -** Represents #8, opening new paths.
278
- 9. **🐱 Cat -** Nine lives, symbolic of #9.
279
-
280
- **Mnemonic:** A mnemonic is a memory aid using patterns or associations to enhance recall. Here, we apply the pegword technique by pairing each number with a vivid image to quickly remember complex information.
281
- *(Adapted from McCarthy, M. J. 2007. Mastering the INFORMATION AGE - A Course in Working Smarter, Thinking Better, and Learning Faster. [1])*
282
-
283
- [1] McCarthy, M. J. 2007. *Mastering the INFORMATION AGE - A Course in Working Smarter, Thinking Better, and Learning Faster*. Retrieved from https://www.example.com/reference
284
- '''
285
-
286
- md_tweet = r'''
287
- # 🐦 Tweet Summary
288
- Unlock your AI mastery with our densified skill tree - from LC to SD - each node paired with powerful mnemonics and vivid visuals (🗼👓🪑🪟✋🎲☁️🚪🐱) to boost memory and innovation. #AI #ML #Learning #Innovation
289
- '''
290
-
291
- # --------------------------
292
- # Combined Mermaid Diagram (Overview)
293
- # --------------------------
294
- combined_mermaid = r'''
295
- graph TD
296
- LeCo["1. 👥 Leadership and Collaboration - LeCo"]
297
- SeCo["2. 🔒 Security and Compliance - SeCo"]
298
- DaEn["3. 📊 Data Engineering - DaEn"]
299
- CoOS["4. 📢 Community Open Source - CoOS"]
300
- FuMo["5. 📱 FullStack UI Mobile - FuMo"]
301
- SoCM["6. 💻 Software Cloud MLOps - SoCM"]
302
- AIML["7. 🤖 AI Machine Learning - AIML"]
303
- SyIn["8. 🔧 Systems Infrastructure - SyIn"]
304
- SpDo["9. 🎯 Specialized Domains - SpDo"]
305
-
306
- LeCo -->|🧭 guides| SeCo
307
- LeCo -->|👑 leads| AIML
308
- LeCo -->|🤝 supports| SyIn
309
- SeCo ---|🔒 secures| AIML
310
- SeCo ---|🛡️ protects| SoCM
311
- AIML -->|💧 feeds| DaEn
312
- SoCM -->|⚡ powers| AIML
313
- FuMo ---|🔌 integrates with| SoCM
314
- FuMo -->|➕ extends to| SpDo
315
- SpDo ---|✨ enhances| AIML
316
- LeCo ---|👁️ oversees| SoCM
317
- CoOS ---|🤝 collaborates with| LeCo
318
- CoOS ---|🗣️ informs| DaEn
319
- SpDo ---|🔄 shares with| CoOS
320
- '''
321
-
322
- # --------------------------
323
- # Streamlit App Layout
324
- # --------------------------
325
- def main():
326
- st.set_page_config(page_title="Densified Skill Tree", layout="wide")
327
-
328
- # Optionally render combined outlines and submodels if desired:
329
- st.markdown(md_combined_outline, unsafe_allow_html=True)
330
- #st.markdown(md_submodels_outline, unsafe_allow_html=True)
331
-
332
- # For each numbered area, display its markdown outline first, then its mermaid diagram.
333
- for key in sorted(markdown_areas.keys(), key=lambda k: int(k.split('.')[0])):
334
- st.markdown(markdown_areas[key], unsafe_allow_html=True)
335
- if key in mermaid_areas:
336
- render_mermaid(mermaid_areas[key], height=350)
337
-
338
- # Render the combined mermaid diagram for an overview
339
- render_mermaid(combined_mermaid, height=850)
340
-
341
- # Display additional markdown sections
342
- st.markdown(md_glossary, unsafe_allow_html=True)
343
- st.markdown(md_python_libraries, unsafe_allow_html=True)
344
- st.markdown(md_js_libraries, unsafe_allow_html=True)
345
- st.markdown(md_picture_mnemonic, unsafe_allow_html=True)
346
- st.markdown(md_tweet, unsafe_allow_html=True)
347
-
348
- if __name__ == "__main__":
349
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Three.js Infinite World</title>
5
+ <style>
6
+ body { margin: 0; overflow: hidden; }
7
+ canvas { display: block; }
8
+ </style>
9
+ <!-- New: Polling function for game state -->
10
+ <script>
11
+ // Poll the shared game state every 5 seconds (for demonstration)
12
+ function pollGameState() {
13
+ console.log("Polling updated game state:", window.GAME_STATE);
14
+ // Here you could update the scene based on the new state.
15
+ }
16
+ setInterval(pollGameState, 5000);
17
+ </script>
18
+ </head>
19
+ <body>
20
+ <script type="importmap">
21
+ {
22
+ "imports": {
23
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
24
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
25
+ }
26
+ }
27
+ </script>
28
+
29
+ <script type="module">
30
+ import * as THREE from 'three';
31
+
32
+ let scene, camera, renderer, playerMesh;
33
+ let raycaster, mouse;
34
+ const keysPressed = {};
35
+ const playerSpeed = 0.15;
36
+ let newlyPlacedObjects = []; // Track objects added THIS session for saving
37
+ const placeholderPlots = new Set();
38
+ const groundMeshes = {}; // Store ground mesh references
39
+
40
+ // --- Session Storage Key ---
41
+ const SESSION_STORAGE_KEY = 'unsavedInfiniteWorldState';
42
+
43
+ // --- Injected State from Streamlit ---
44
+ const allInitialObjects = window.ALL_INITIAL_OBJECTS || [];
45
+ const plotsMetadata = window.PLOTS_METADATA || [];
46
+ const selectedObjectType = window.SELECTED_OBJECT_TYPE || "None";
47
+ const plotWidth = window.PLOT_WIDTH || 50.0;
48
+ const plotDepth = window.PLOT_DEPTH || 50.0;
49
+
50
+ const groundMaterial = new THREE.MeshStandardMaterial({
51
+ color: 0x55aa55, roughness: 0.9, metalness: 0.1, side: THREE.DoubleSide
52
+ });
53
+ const placeholderGroundMaterial = new THREE.MeshStandardMaterial({
54
+ color: 0x448844, roughness: 0.95, metalness: 0.1, side: THREE.DoubleSide
55
+ });
56
+
57
+ function init() {
58
+ scene = new THREE.Scene();
59
+ scene.background = new THREE.Color(0xabcdef);
60
+ const aspect = window.innerWidth / window.innerHeight;
61
+ camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 4000);
62
+ camera.position.set(0, 15, 20);
63
+ camera.lookAt(0, 0, 0);
64
+ scene.add(camera);
65
+
66
+ setupLighting();
67
+ setupInitialGround();
68
+ setupPlayer();
69
+
70
+ raycaster = new THREE.Raycaster();
71
+ mouse = new THREE.Vector2();
72
+
73
+ renderer = new THREE.WebGLRenderer({ antialias: true });
74
+ renderer.setSize(window.innerWidth, window.innerHeight);
75
+ renderer.shadowMap.enabled = true;
76
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
77
+ document.body.appendChild(renderer.domElement);
78
+
79
+ loadInitialObjects();
80
+ restoreUnsavedState();
81
+
82
+ // Event Listeners
83
+ document.addEventListener('mousemove', onMouseMove, false);
84
+ document.addEventListener('click', onDocumentClick, false);
85
+ window.addEventListener('resize', onWindowResize, false);
86
+ document.addEventListener('keydown', onKeyDown);
87
+ document.addEventListener('keyup', onKeyUp);
88
+
89
+ // Define functions callable by Streamlit
90
+ window.teleportPlayer = teleportPlayer;
91
+ window.getSaveDataAndPosition = getSaveDataAndPosition;
92
+ window.resetNewlyPlacedObjects = resetNewlyPlacedObjects;
93
+
94
+ console.log("Three.js Initialized. World ready.");
95
+ animate();
96
+ }
97
+
98
+ function setupLighting() {
99
+ const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
100
+ scene.add(ambientLight);
101
+ const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
102
+ directionalLight.position.set(50, 150, 100);
103
+ directionalLight.castShadow = true;
104
+ directionalLight.shadow.mapSize.width = 4096;
105
+ directionalLight.shadow.mapSize.height = 4096;
106
+ directionalLight.shadow.camera.near = 0.5;
107
+ directionalLight.shadow.camera.far = 500;
108
+ directionalLight.shadow.camera.left = -150;
109
+ directionalLight.shadow.camera.right = 150;
110
+ directionalLight.shadow.camera.top = 150;
111
+ directionalLight.shadow.camera.bottom = -150;
112
+ directionalLight.shadow.bias = -0.001;
113
+ scene.add(directionalLight);
114
+ }
115
+
116
+ function setupInitialGround() {
117
+ console.log(`Setting up initial ground for ${plotsMetadata.length} plots.`);
118
+ plotsMetadata.forEach(plot => {
119
+ createGroundPlane(plot.grid_x, plot.grid_z, false);
120
+ });
121
+ if (plotsMetadata.length === 0) {
122
+ createGroundPlane(0, 0, false);
123
+ }
124
+ }
125
+
126
+ function createGroundPlane(gridX, gridZ, isPlaceholder) {
127
+ const gridKey = `${gridX}_${gridZ}`;
128
+ if (groundMeshes[gridKey]) return;
129
+ console.log(`Creating ${isPlaceholder ? 'placeholder' : 'initial'} ground at ${gridX}, ${gridZ}`);
130
+ const groundGeometry = new THREE.PlaneGeometry(plotWidth, plotDepth);
131
+ const material = isPlaceholder ? placeholderGroundMaterial : groundMaterial;
132
+ const groundMesh = new THREE.Mesh(groundGeometry, material);
133
+ groundMesh.rotation.x = -Math.PI / 2;
134
+ groundMesh.position.y = -0.05;
135
+ groundMesh.position.x = gridX * plotWidth + plotWidth / 2.0;
136
+ groundMesh.position.z = gridZ * plotDepth + plotDepth / 2.0;
137
+ groundMesh.receiveShadow = true;
138
+ groundMesh.userData.gridKey = gridKey;
139
+ scene.add(groundMesh);
140
+ groundMeshes[gridKey] = groundMesh;
141
+ if (isPlaceholder) placeholderPlots.add(gridKey);
142
+ }
143
+
144
+ function setupPlayer() {
145
+ const playerGeo = new THREE.CapsuleGeometry(0.4, 0.8, 4, 8);
146
+ const playerMat = new THREE.MeshStandardMaterial({ color: 0x0000ff, roughness: 0.6 });
147
+ playerMesh = new THREE.Mesh(playerGeo, playerMat);
148
+ playerMesh.position.set(plotWidth / 2, 0.4 + 0.8/2, plotDepth/2);
149
+ playerMesh.castShadow = true;
150
+ playerMesh.receiveShadow = true;
151
+ scene.add(playerMesh);
152
+ }
153
+
154
+ function loadInitialObjects() {
155
+ console.log(`Loading ${allInitialObjects.length} initial objects from Python.`);
156
+ allInitialObjects.forEach(objData => { createAndPlaceObject(objData, false); });
157
+ console.log("Finished loading initial objects.");
158
+ }
159
+
160
+ function createAndPlaceObject(objData, isNewObject) {
161
+ let loadedObject = null;
162
+ switch (objData.type) {
163
+ case "Simple House": loadedObject = createSimpleHouse(); break;
164
+ case "Tree": loadedObject = createTree(); break;
165
+ case "Rock": loadedObject = createRock(); break;
166
+ case "Fence Post": loadedObject = createFencePost(); break;
167
+ default: console.warn("Unknown object type in data:", objData.type); break;
168
+ }
169
+ if (loadedObject) {
170
+ if (objData.position && objData.position.x !== undefined) {
171
+ loadedObject.position.set(objData.position.x, objData.position.y, objData.position.z);
172
+ } else if (objData.pos_x !== undefined) {
173
+ loadedObject.position.set(objData.pos_x, objData.pos_y, objData.pos_z);
174
+ }
175
+ if (objData.rotation) {
176
+ loadedObject.rotation.set(objData.rotation._x, objData.rotation._y, objData.rotation._z, objData.rotation._order || 'XYZ');
177
+ } else if (objData.rot_x !== undefined) {
178
+ loadedObject.rotation.set(objData.rot_x, objData.rot_y, objData.rot_z, objData.rot_order || 'XYZ');
179
+ }
180
+ loadedObject.userData.obj_id = objData.obj_id || loadedObject.userData.obj_id;
181
+ scene.add(loadedObject);
182
+ if (isNewObject) newlyPlacedObjects.push(loadedObject);
183
+ return loadedObject;
184
+ }
185
+ return null;
186
+ }
187
+
188
+ function saveUnsavedState() {
189
+ try {
190
+ const stateToSave = newlyPlacedObjects.map(obj => ({
191
+ obj_id: obj.userData.obj_id,
192
+ type: obj.userData.type,
193
+ position: { x: obj.position.x, y: obj.position.y, z: obj.position.z },
194
+ rotation: { _x: obj.rotation.x, _y: obj.rotation.y, _z: obj.rotation.z, _order: obj.rotation.order }
195
+ }));
196
+ sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(stateToSave));
197
+ console.log(`Saved ${stateToSave.length} unsaved objects to sessionStorage.`);
198
+ } catch (e) {
199
+ console.error("Error saving state to sessionStorage:", e);
200
+ }
201
+ }
202
+
203
+ function restoreUnsavedState() {
204
+ try {
205
+ const savedState = sessionStorage.getItem(SESSION_STORAGE_KEY);
206
+ if (savedState) {
207
+ console.log("Found unsaved state in sessionStorage. Restoring...");
208
+ const objectsToRestore = JSON.parse(savedState);
209
+ if (Array.isArray(objectsToRestore)) {
210
+ newlyPlacedObjects = [];
211
+ let count = 0;
212
+ objectsToRestore.forEach(objData => {
213
+ if(createAndPlaceObject(objData, true)) { count++; }
214
+ });
215
+ console.log(`Restored ${count} objects.`);
216
+ }
217
+ } else {
218
+ console.log("No unsaved state found in sessionStorage.");
219
+ }
220
+ } catch (e) {
221
+ console.error("Error restoring state from sessionStorage:", e);
222
+ sessionStorage.removeItem(SESSION_STORAGE_KEY);
223
+ }
224
+ }
225
+
226
+ function clearUnsavedState() {
227
+ sessionStorage.removeItem(SESSION_STORAGE_KEY);
228
+ newlyPlacedObjects = [];
229
+ console.log("Cleared unsaved state from memory and sessionStorage.");
230
+ }
231
+
232
+ function createObjectBase(type) {
233
+ return { userData: { type: type, obj_id: THREE.MathUtils.generateUUID() } };
234
+ }
235
+
236
+ function createSimpleHouse() {
237
+ const base = createObjectBase("Simple House");
238
+ const group = new THREE.Group();
239
+ Object.assign(group, base);
240
+ const mat1 = new THREE.MeshStandardMaterial({color:0xffccaa, roughness:0.8});
241
+ const mat2 = new THREE.MeshStandardMaterial({color:0xaa5533, roughness:0.7});
242
+ const m1 = new THREE.Mesh(new THREE.BoxGeometry(2,1.5,2.5), mat1);
243
+ m1.position.y = 1.5/2;
244
+ m1.castShadow = true;
245
+ m1.receiveShadow = true;
246
+ group.add(m1);
247
+ const m2 = new THREE.Mesh(new THREE.ConeGeometry(1.8,1,4), mat2);
248
+ m2.position.y = 1.5+1/2;
249
+ m2.rotation.y = Math.PI/4;
250
+ m2.castShadow = true;
251
+ m2.receiveShadow = true;
252
+ group.add(m2);
253
+ return group;
254
+ }
255
+
256
+ function createTree() {
257
+ const base = createObjectBase("Tree");
258
+ const group = new THREE.Group();
259
+ Object.assign(group, base);
260
+ const mat1 = new THREE.MeshStandardMaterial({color:0x8B4513, roughness:0.9});
261
+ const mat2 = new THREE.MeshStandardMaterial({color:0x228B22, roughness:0.8});
262
+ const m1 = new THREE.Mesh(new THREE.CylinderGeometry(0.3,0.4,2,8), mat1);
263
+ m1.position.y = 1;
264
+ m1.castShadow = true;
265
+ m1.receiveShadow = true;
266
+ group.add(m1);
267
+ const m2 = new THREE.Mesh(new THREE.IcosahedronGeometry(1.2,0), mat2);
268
+ m2.position.y = 2.8;
269
+ m2.castShadow = true;
270
+ m2.receiveShadow = true;
271
+ group.add(m2);
272
+ return group;
273
+ }
274
+
275
+ function createRock() {
276
+ const base = createObjectBase("Rock");
277
+ const mat = new THREE.MeshStandardMaterial({color:0xaaaaaa, roughness:0.8, metalness:0.1});
278
+ const rock = new THREE.Mesh(new THREE.IcosahedronGeometry(0.7,0), mat);
279
+ Object.assign(rock, base);
280
+ rock.position.y = 0.35;
281
+ rock.rotation.set(Math.random()*Math.PI, Math.random()*Math.PI, 0);
282
+ rock.castShadow = true;
283
+ rock.receiveShadow = true;
284
+ return rock;
285
+ }
286
+
287
+ function createFencePost() {
288
+ const base = createObjectBase("Fence Post");
289
+ const mat = new THREE.MeshStandardMaterial({color:0xdeb887, roughness:0.9});
290
+ const post = new THREE.Mesh(new THREE.BoxGeometry(0.2,1.5,0.2), mat);
291
+ Object.assign(post, base);
292
+ post.position.y = 0.75;
293
+ post.castShadow = true;
294
+ post.receiveShadow = true;
295
+ return post;
296
+ }
297
+
298
+ function onMouseMove(event) {
299
+ mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
300
+ mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
301
+ }
302
+
303
+ function onDocumentClick(event) {
304
+ if (selectedObjectType === "None") return;
305
+ const groundCandidates = Object.values(groundMeshes);
306
+ if (groundCandidates.length === 0) return;
307
+ raycaster.setFromCamera(mouse, camera);
308
+ const intersects = raycaster.intersectObjects(groundCandidates);
309
+ if (intersects.length > 0) {
310
+ const intersectPoint = intersects[0].point;
311
+ let newObjectToPlace = null;
312
+ switch (selectedObjectType) {
313
+ case "Simple House": newObjectToPlace = createSimpleHouse(); break;
314
+ case "Tree": newObjectToPlace = createTree(); break;
315
+ case "Rock": newObjectToPlace = createRock(); break;
316
+ case "Fence Post": newObjectToPlace = createFencePost(); break;
317
+ default: return;
318
+ }
319
+ if (newObjectToPlace) {
320
+ newObjectToPlace.position.copy(intersectPoint);
321
+ newObjectToPlace.position.y += 0.01;
322
+ scene.add(newObjectToPlace);
323
+ newlyPlacedObjects.push(newObjectToPlace);
324
+ saveUnsavedState();
325
+ console.log(`Placed new ${selectedObjectType}. Total unsaved: ${newlyPlacedObjects.length}`);
326
+ }
327
+ }
328
+ }
329
+
330
+ function onKeyDown(event) { keysPressed[event.code] = true; }
331
+ function onKeyUp(event) { keysPressed[event.code] = false; }
332
+
333
+ function teleportPlayer(targetX, targetZ) {
334
+ console.log(`JS teleportPlayer called with targetX: ${targetX}, targetZ: ${targetZ}`);
335
+ if (playerMesh) {
336
+ playerMesh.position.x = targetX;
337
+ playerMesh.position.z = targetZ;
338
+ const offset = new THREE.Vector3(0, 15, 20);
339
+ const targetPosition = playerMesh.position.clone().add(offset);
340
+ camera.position.copy(targetPosition);
341
+ camera.lookAt(playerMesh.position);
342
+ console.log("Player teleported to:", playerMesh.position);
343
+ } else {
344
+ console.error("Player mesh not found for teleport.");
345
+ }
346
+ }
347
+
348
+ function getSaveDataAndPosition() {
349
+ console.log(`JS getSaveDataAndPosition called. Found ${newlyPlacedObjects.length} new objects.`);
350
+ const objectsToSave = newlyPlacedObjects.map(obj => {
351
+ if (!obj.userData || !obj.userData.type) { return null; }
352
+ const rotation = { _x: obj.rotation.x, _y: obj.rotation.y, _z: obj.rotation.z, _order: obj.rotation.order };
353
+ return {
354
+ obj_id: obj.userData.obj_id, type: obj.userData.type,
355
+ position: { x: obj.position.x, y: obj.position.y, z: obj.position.z },
356
+ rotation: rotation
357
+ };
358
+ }).filter(obj => obj !== null);
359
+ const playerPos = playerMesh ? { x: playerMesh.position.x, y: playerMesh.position.y, z: playerMesh.position.z } : {x:0, y:0, z:0};
360
+ const payload = {
361
+ playerPosition: playerPos,
362
+ objectsToSave: objectsToSave
363
+ };
364
+ console.log("Prepared payload for saving:", payload);
365
+ return JSON.stringify(payload);
366
+ }
367
+
368
+ function resetNewlyPlacedObjects() {
369
+ console.log(`JS resetNewlyPlacedObjects called.`);
370
+ clearUnsavedState();
371
+ }
372
+
373
+ function updatePlayerMovement() {
374
+ if (!playerMesh) return;
375
+ const moveDirection = new THREE.Vector3(0, 0, 0);
376
+ if (keysPressed['KeyW'] || keysPressed['ArrowUp']) moveDirection.z -= 1;
377
+ if (keysPressed['KeyS'] || keysPressed['ArrowDown']) moveDirection.z += 1;
378
+ if (keysPressed['KeyA'] || keysPressed['ArrowLeft']) moveDirection.x -= 1;
379
+ if (keysPressed['KeyD'] || keysPressed['ArrowRight']) moveDirection.x += 1;
380
+ if (moveDirection.lengthSq() > 0) {
381
+ moveDirection.normalize().multiplyScalar(playerSpeed);
382
+ const forward = new THREE.Vector3();
383
+ camera.getWorldDirection(forward);
384
+ forward.y = 0;
385
+ forward.normalize();
386
+ const right = new THREE.Vector3().crossVectors(camera.up, forward).normalize();
387
+ const worldMove = new THREE.Vector3();
388
+ worldMove.add(forward.multiplyScalar(-moveDirection.z));
389
+ worldMove.add(right.multiplyScalar(-moveDirection.x));
390
+ worldMove.normalize().multiplyScalar(playerSpeed);
391
+ playerMesh.position.add(worldMove);
392
+ playerMesh.position.y = Math.max(playerMesh.position.y, 0.4 + 0.8/2);
393
+ checkAndExpandGround();
394
+ }
395
+ }
396
+
397
+ function checkAndExpandGround() {
398
+ if (!playerMesh) return;
399
+ const currentGridX = Math.floor(playerMesh.position.x / plotWidth);
400
+ const currentGridZ = Math.floor(playerMesh.position.z / plotDepth);
401
+ for (let dx = -1; dx <= 1; dx++) {
402
+ for (let dz = -1; dz <= 1; dz++) {
403
+ if (dx === 0 && dz === 0) continue;
404
+ const checkX = currentGridX + dx;
405
+ const checkZ = currentGridZ + dz;
406
+ const gridKey = `${checkX}_${checkZ}`;
407
+ if (!groundMeshes[gridKey]) {
408
+ const isSavedPlot = plotsMetadata.some(plot => plot.grid_x === checkX && plot.grid_z === checkZ);
409
+ if (!isSavedPlot) {
410
+ createGroundPlane(checkX, checkZ, true);
411
+ }
412
+ }
413
+ }
414
+ }
415
+ }
416
+
417
+ function updateCamera() {
418
+ if (!playerMesh) return;
419
+ const offset = new THREE.Vector3(0, 15, 20);
420
+ const targetPosition = playerMesh.position.clone().add(offset);
421
+ camera.position.lerp(targetPosition, 0.08);
422
+ camera.lookAt(playerMesh.position);
423
+ }
424
+
425
+ function onWindowResize() {
426
+ camera.aspect = window.innerWidth / window.innerHeight;
427
+ camera.updateProjectionMatrix();
428
+ renderer.setSize(window.innerWidth, window.innerHeight);
429
+ }
430
+
431
+ function animate() {
432
+ requestAnimationFrame(animate);
433
+ updatePlayerMovement();
434
+ updateCamera();
435
+ renderer.render(scene, camera);
436
+ }
437
+
438
+ init();
439
+ </script>
440
+ </body>
441
+ </html>