Update app.py
Browse files
app.py
CHANGED
@@ -1,38 +1,86 @@
|
|
1 |
#!/usr/bin/env python3
|
2 |
import os
|
3 |
import re
|
4 |
-
import glob
|
5 |
import streamlit as st
|
6 |
import streamlit.components.v1 as components
|
7 |
-
from transformers import pipeline
|
8 |
from urllib.parse import quote
|
9 |
-
from datetime import datetime
|
10 |
-
import pytz
|
11 |
-
import base64
|
12 |
import pandas as pd
|
13 |
import torch
|
14 |
import torch.nn as nn
|
15 |
import torch.optim as optim
|
16 |
from torch.utils.data import DataLoader, TensorDataset
|
|
|
17 |
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
|
|
20 |
trees = {
|
21 |
-
"
|
22 |
-
0.
|
23 |
-
1.
|
24 |
-
-
|
25 |
-
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
""",
|
28 |
-
"AI Topics": """
|
29 |
-
1. Major AI Industry Players ๐
|
30 |
-
1. Research Leaders ๐ฏ
|
31 |
-
- OpenAI: GPT-4 DALL-E Foundation Models ๐ต
|
32 |
-
"""
|
33 |
}
|
34 |
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
lines = outline_text.strip().split('\n')
|
37 |
nodes, edges, clicks, stack = [], [], [], []
|
38 |
for line in lines:
|
@@ -41,8 +89,10 @@ def parse_outline_to_mermaid(outline_text):
|
|
41 |
label = re.sub(r'^[#*\->\d\.\s]+', '', line.strip())
|
42 |
if label:
|
43 |
node_id = f"N{len(nodes)}"
|
|
|
44 |
nodes.append(f'{node_id}["{label}"]')
|
45 |
-
|
|
|
46 |
if stack:
|
47 |
parent_level = stack[-1][0]
|
48 |
if level > parent_level:
|
@@ -59,6 +109,7 @@ def parse_outline_to_mermaid(outline_text):
|
|
59 |
return "%%{init: {'themeVariables': {'fontSize': '18px'}}}%%\nflowchart LR\n" + "\n".join(nodes + edges + clicks)
|
60 |
|
61 |
def generate_mermaid_html(mermaid_code):
|
|
|
62 |
return f"""
|
63 |
<html><head><script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
64 |
<style>.centered-mermaid{{display:flex;justify-content:center;margin:20px auto;}}</style></head>
|
@@ -67,6 +118,7 @@ def generate_mermaid_html(mermaid_code):
|
|
67 |
"""
|
68 |
|
69 |
def grow_tree(base_tree, new_node_name, parent_node):
|
|
|
70 |
lines = base_tree.strip().split('\n')
|
71 |
new_lines = []
|
72 |
added = False
|
@@ -79,32 +131,34 @@ def grow_tree(base_tree, new_node_name, parent_node):
|
|
79 |
return "\n".join(new_lines)
|
80 |
|
81 |
def get_download_link(file_path, mime_type="text/plain"):
|
|
|
82 |
with open(file_path, 'rb') as f:
|
83 |
data = f.read()
|
84 |
b64 = base64.b64encode(data).decode()
|
85 |
return f'<a href="data:{mime_type};base64,{b64}" download="{file_path}">Download {file_path}</a>'
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
# Main App
|
92 |
st.title("๐ณ AI Knowledge Tree Builder ๐ฑ")
|
93 |
|
|
|
|
|
94 |
if 'current_tree' not in st.session_state:
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
st.session_state['current_tree'] = trees["Biology"]
|
100 |
-
|
101 |
-
selected_tree = st.selectbox("Select Knowledge Tree", list(trees.keys()))
|
102 |
-
if selected_tree != st.session_state.get('selected_tree_name', 'Biology'):
|
103 |
-
st.session_state['current_tree'] = trees[selected_tree]
|
104 |
-
st.session_state['selected_tree_name'] = selected_tree
|
105 |
-
with open("current_tree.md", "w") as f:
|
106 |
-
f.write(st.session_state['current_tree'])
|
107 |
|
|
|
108 |
new_node = st.text_input("Add New Node")
|
109 |
parent_node = st.text_input("Parent Node")
|
110 |
if st.button("Grow Tree ๐ฑ") and new_node and parent_node:
|
@@ -113,42 +167,46 @@ if st.button("Grow Tree ๐ฑ") and new_node and parent_node:
|
|
113 |
f.write(st.session_state['current_tree'])
|
114 |
st.success(f"Added '{new_node}' under '{parent_node}'!")
|
115 |
|
|
|
116 |
st.markdown("### Knowledge Tree Visualization")
|
117 |
-
mermaid_code = parse_outline_to_mermaid(st.session_state['current_tree'])
|
118 |
components.html(generate_mermaid_html(mermaid_code), height=600)
|
119 |
|
|
|
120 |
if st.button("Export Tree as Markdown"):
|
121 |
export_md = f"# Knowledge Tree\n\n## Outline\n{st.session_state['current_tree']}\n\n## Mermaid Diagram\n```mermaid\n{mermaid_code}\n```"
|
122 |
with open("knowledge_tree.md", "w") as f:
|
123 |
f.write(export_md)
|
124 |
st.markdown(get_download_link("knowledge_tree.md", "text/markdown"), unsafe_allow_html=True)
|
125 |
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
|
|
|
|
152 |
import streamlit as st
|
153 |
import torch
|
154 |
import torch.nn as nn
|
@@ -166,12 +224,12 @@ if st.button("Predict"):
|
|
166 |
prediction = model(input_tensor).item()
|
167 |
st.write(f"Predicted {target_col}: {{prediction}}")
|
168 |
"""
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
# ML Model Demo
|
176 |
|
177 |
## How to run
|
@@ -179,9 +237,9 @@ if st.button("Predict"):
|
|
179 |
2. Run the app: `streamlit run app.py`
|
180 |
3. Input feature values and click "Predict".
|
181 |
"""
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
|
|
1 |
#!/usr/bin/env python3
|
2 |
import os
|
3 |
import re
|
|
|
4 |
import streamlit as st
|
5 |
import streamlit.components.v1 as components
|
|
|
6 |
from urllib.parse import quote
|
|
|
|
|
|
|
7 |
import pandas as pd
|
8 |
import torch
|
9 |
import torch.nn as nn
|
10 |
import torch.optim as optim
|
11 |
from torch.utils.data import DataLoader, TensorDataset
|
12 |
+
import base64
|
13 |
|
14 |
+
# Page Configuration
|
15 |
+
st.set_page_config(
|
16 |
+
page_title="AI Knowledge Tree Builder ๐๐ฟ",
|
17 |
+
page_icon="๐ณโจ",
|
18 |
+
layout="wide",
|
19 |
+
initial_sidebar_state="auto",
|
20 |
+
)
|
21 |
|
22 |
+
# Predefined Knowledge Trees
|
23 |
trees = {
|
24 |
+
"ML Engineering": """
|
25 |
+
0. ML Engineering ๐
|
26 |
+
1. Data Preparation
|
27 |
+
- Load Data ๐
|
28 |
+
- Preprocess Data ๐ ๏ธ
|
29 |
+
2. Model Building
|
30 |
+
- Train Model ๐ค
|
31 |
+
- Evaluate Model ๐
|
32 |
+
3. Deployment
|
33 |
+
- Deploy Model ๐
|
34 |
+
""",
|
35 |
+
"Health": """
|
36 |
+
0. Health and Wellness ๐ฟ
|
37 |
+
1. Physical Health
|
38 |
+
- Exercise ๐๏ธ
|
39 |
+
- Nutrition ๐
|
40 |
+
2. Mental Health
|
41 |
+
- Meditation ๐ง
|
42 |
+
- Therapy ๐๏ธ
|
43 |
+
""",
|
44 |
+
}
|
45 |
+
|
46 |
+
# Project Seeds
|
47 |
+
project_seeds = {
|
48 |
+
"Code Project": """
|
49 |
+
0. Code Project ๐
|
50 |
+
1. app.py ๐
|
51 |
+
2. requirements.txt ๐ฆ
|
52 |
+
3. README.md ๐
|
53 |
+
""",
|
54 |
+
"Papers Project": """
|
55 |
+
0. Papers Project ๐
|
56 |
+
1. markdown ๐
|
57 |
+
2. mermaid ๐ผ๏ธ
|
58 |
+
3. huggingface.co ๐ค
|
59 |
+
""",
|
60 |
+
"AI Project": """
|
61 |
+
0. AI Project ๐ค
|
62 |
+
1. Streamlit Torch Transformers
|
63 |
+
- Streamlit ๐
|
64 |
+
- Torch ๐ฅ
|
65 |
+
- Transformers ๐ค
|
66 |
+
2. DistillKit MergeKit Spectrum
|
67 |
+
- DistillKit ๐งช
|
68 |
+
- MergeKit ๐
|
69 |
+
- Spectrum ๐
|
70 |
+
3. Transformers Diffusers Datasets
|
71 |
+
- Transformers ๐ค
|
72 |
+
- Diffusers ๐จ
|
73 |
+
- Datasets ๐
|
74 |
""",
|
|
|
|
|
|
|
|
|
|
|
75 |
}
|
76 |
|
77 |
+
# Utility Functions
|
78 |
+
def sanitize_label(label):
|
79 |
+
"""Remove invalid characters for Mermaid labels."""
|
80 |
+
return re.sub(r'[^\w\s-]', '', label).replace(' ', '_')
|
81 |
+
|
82 |
+
def parse_outline_to_mermaid(outline_text, search_agent):
|
83 |
+
"""Convert tree outline to Mermaid syntax with clickable nodes."""
|
84 |
lines = outline_text.strip().split('\n')
|
85 |
nodes, edges, clicks, stack = [], [], [], []
|
86 |
for line in lines:
|
|
|
89 |
label = re.sub(r'^[#*\->\d\.\s]+', '', line.strip())
|
90 |
if label:
|
91 |
node_id = f"N{len(nodes)}"
|
92 |
+
sanitized_label = sanitize_label(label)
|
93 |
nodes.append(f'{node_id}["{label}"]')
|
94 |
+
search_url = search_urls[search_agent](label)
|
95 |
+
clicks.append(f'click {node_id} "{search_url}" _blank')
|
96 |
if stack:
|
97 |
parent_level = stack[-1][0]
|
98 |
if level > parent_level:
|
|
|
109 |
return "%%{init: {'themeVariables': {'fontSize': '18px'}}}%%\nflowchart LR\n" + "\n".join(nodes + edges + clicks)
|
110 |
|
111 |
def generate_mermaid_html(mermaid_code):
|
112 |
+
"""Generate HTML to display Mermaid diagram."""
|
113 |
return f"""
|
114 |
<html><head><script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
115 |
<style>.centered-mermaid{{display:flex;justify-content:center;margin:20px auto;}}</style></head>
|
|
|
118 |
"""
|
119 |
|
120 |
def grow_tree(base_tree, new_node_name, parent_node):
|
121 |
+
"""Add a new node to the tree under a specified parent."""
|
122 |
lines = base_tree.strip().split('\n')
|
123 |
new_lines = []
|
124 |
added = False
|
|
|
131 |
return "\n".join(new_lines)
|
132 |
|
133 |
def get_download_link(file_path, mime_type="text/plain"):
|
134 |
+
"""Generate a download link for a file."""
|
135 |
with open(file_path, 'rb') as f:
|
136 |
data = f.read()
|
137 |
b64 = base64.b64encode(data).decode()
|
138 |
return f'<a href="data:{mime_type};base64,{b64}" download="{file_path}">Download {file_path}</a>'
|
139 |
|
140 |
+
# Search Agents (Highest resolution social network default: X)
|
141 |
+
search_urls = {
|
142 |
+
"๐๐ArXiv": lambda k: f"/?q={quote(k)}",
|
143 |
+
"๐ฎGoogle": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
144 |
+
"๐บYoutube": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
145 |
+
"๐ญBing": lambda k: f"https://www.bing.com/search?q={quote(k)}",
|
146 |
+
"๐กTruth": lambda k: f"https://truthsocial.com/search?q={quote(k)}",
|
147 |
+
"๐ฑX": lambda k: f"https://twitter.com/search?q={quote(k)}",
|
148 |
+
}
|
149 |
|
150 |
# Main App
|
151 |
st.title("๐ณ AI Knowledge Tree Builder ๐ฑ")
|
152 |
|
153 |
+
# Select Project Type
|
154 |
+
project_type = st.selectbox("Select Project Type", ["Code Project", "Papers Project", "AI Project"])
|
155 |
if 'current_tree' not in st.session_state:
|
156 |
+
st.session_state['current_tree'] = trees.get("ML Engineering", project_seeds[project_type])
|
157 |
+
|
158 |
+
# Select Search Agent for Node Links
|
159 |
+
search_agent = st.selectbox("Select Search Agent for Node Links", list(search_urls.keys()), index=5) # Default to X
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
|
161 |
+
# Tree Growth
|
162 |
new_node = st.text_input("Add New Node")
|
163 |
parent_node = st.text_input("Parent Node")
|
164 |
if st.button("Grow Tree ๐ฑ") and new_node and parent_node:
|
|
|
167 |
f.write(st.session_state['current_tree'])
|
168 |
st.success(f"Added '{new_node}' under '{parent_node}'!")
|
169 |
|
170 |
+
# Display Mermaid Diagram
|
171 |
st.markdown("### Knowledge Tree Visualization")
|
172 |
+
mermaid_code = parse_outline_to_mermaid(st.session_state['current_tree'], search_agent)
|
173 |
components.html(generate_mermaid_html(mermaid_code), height=600)
|
174 |
|
175 |
+
# Export Tree
|
176 |
if st.button("Export Tree as Markdown"):
|
177 |
export_md = f"# Knowledge Tree\n\n## Outline\n{st.session_state['current_tree']}\n\n## Mermaid Diagram\n```mermaid\n{mermaid_code}\n```"
|
178 |
with open("knowledge_tree.md", "w") as f:
|
179 |
f.write(export_md)
|
180 |
st.markdown(get_download_link("knowledge_tree.md", "text/markdown"), unsafe_allow_html=True)
|
181 |
|
182 |
+
# AI Project: Minimal ML Model Building
|
183 |
+
if project_type == "AI Project":
|
184 |
+
st.subheader("Build Minimal ML Model from CSV")
|
185 |
+
uploaded_file = st.file_uploader("Upload CSV", type="csv")
|
186 |
+
if uploaded_file:
|
187 |
+
df = pd.read_csv(uploaded_file)
|
188 |
+
st.write("Columns:", df.columns.tolist())
|
189 |
+
feature_cols = st.multiselect("Select feature columns", df.columns)
|
190 |
+
target_col = st.selectbox("Select target column", df.columns)
|
191 |
+
if st.button("Train Model"):
|
192 |
+
X = df[feature_cols].values
|
193 |
+
y = df[target_col].values
|
194 |
+
X_tensor = torch.tensor(X, dtype=torch.float32)
|
195 |
+
y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1)
|
196 |
+
dataset = TensorDataset(X_tensor, y_tensor)
|
197 |
+
loader = DataLoader(dataset, batch_size=32, shuffle=True)
|
198 |
+
model = nn.Linear(X.shape[1], 1)
|
199 |
+
criterion = nn.MSELoss()
|
200 |
+
optimizer = optim.Adam(model.parameters(), lr=0.01)
|
201 |
+
for epoch in range(10):
|
202 |
+
for batch_X, batch_y in loader:
|
203 |
+
optimizer.zero_grad()
|
204 |
+
outputs = model(batch_X)
|
205 |
+
loss = criterion(outputs, batch_y)
|
206 |
+
loss.backward()
|
207 |
+
optimizer.step()
|
208 |
+
torch.save(model.state_dict(), "model.pth")
|
209 |
+
app_code = f"""
|
210 |
import streamlit as st
|
211 |
import torch
|
212 |
import torch.nn as nn
|
|
|
224 |
prediction = model(input_tensor).item()
|
225 |
st.write(f"Predicted {target_col}: {{prediction}}")
|
226 |
"""
|
227 |
+
with open("app.py", "w") as f:
|
228 |
+
f.write(app_code)
|
229 |
+
reqs = "streamlit\ntorch\npandas\n"
|
230 |
+
with open("requirements.txt", "w") as f:
|
231 |
+
f.write(reqs)
|
232 |
+
readme = """
|
233 |
# ML Model Demo
|
234 |
|
235 |
## How to run
|
|
|
237 |
2. Run the app: `streamlit run app.py`
|
238 |
3. Input feature values and click "Predict".
|
239 |
"""
|
240 |
+
with open("README.md", "w") as f:
|
241 |
+
f.write(readme)
|
242 |
+
st.markdown(get_download_link("model.pth", "application/octet-stream"), unsafe_allow_html=True)
|
243 |
+
st.markdown(get_download_link("app.py", "text/plain"), unsafe_allow_html=True)
|
244 |
+
st.markdown(get_download_link("requirements.txt", "text/plain"), unsafe_allow_html=True)
|
245 |
+
st.markdown(get_download_link("README.md", "text/markdown"), unsafe_allow_html=True)
|