awacke1 commited on
Commit
ac04dd1
ยท
verified ยท
1 Parent(s): 912ec24

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -73
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
- st.set_page_config(page_title="AI Knowledge Tree Builder ๐Ÿ“ˆ๐ŸŒฟ", page_icon="๐ŸŒณโœจ", layout="wide")
 
 
 
 
 
 
19
 
 
20
  trees = {
21
- "Biology": """
22
- 0. Biology Core Rules and Future Exceptions
23
- 1. Central Dogma DNA RNA Protein
24
- - Current CRISPR RNA editing ๐Ÿงช
25
- - Research Gene therapy siRNA ๐Ÿ”ฌ
26
- - Future Programmable genetics ๐Ÿš€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- def parse_outline_to_mermaid(outline_text):
 
 
 
 
 
 
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
- clicks.append(f'click {node_id} "?q={quote(label)}" _blank')
 
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
- @st.cache_resource
88
- def load_generator():
89
- return pipeline("text-generation", model="distilgpt2")
 
 
 
 
 
 
90
 
91
  # Main App
92
  st.title("๐ŸŒณ AI Knowledge Tree Builder ๐ŸŒฑ")
93
 
 
 
94
  if 'current_tree' not in st.session_state:
95
- if os.path.exists("current_tree.md"):
96
- with open("current_tree.md", "r") as f:
97
- st.session_state['current_tree'] = f.read()
98
- else:
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
- st.subheader("Build ML Model from CSV")
127
- uploaded_file = st.file_uploader("Upload CSV", type="csv")
128
- if uploaded_file:
129
- df = pd.read_csv(uploaded_file)
130
- st.write("Columns:", df.columns.tolist())
131
- feature_cols = st.multiselect("Select feature columns", df.columns)
132
- target_col = st.selectbox("Select target column", df.columns)
133
- if st.button("Train Model"):
134
- X = df[feature_cols].values
135
- y = df[target_col].values
136
- X_tensor = torch.tensor(X, dtype=torch.float32)
137
- y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1)
138
- dataset = TensorDataset(X_tensor, y_tensor)
139
- loader = DataLoader(dataset, batch_size=32, shuffle=True)
140
- model = nn.Linear(X.shape[1], 1)
141
- criterion = nn.MSELoss()
142
- optimizer = optim.Adam(model.parameters(), lr=0.01)
143
- for epoch in range(10):
144
- for batch_X, batch_y in loader:
145
- optimizer.zero_grad()
146
- outputs = model(batch_X)
147
- loss = criterion(outputs, batch_y)
148
- loss.backward()
149
- optimizer.step()
150
- torch.save(model.state_dict(), "model.pth")
151
- app_code = f"""
 
 
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
- with open("app.py", "w") as f:
170
- f.write(app_code)
171
- reqs = "streamlit\ntorch\npandas\n"
172
- with open("requirements.txt", "w") as f:
173
- f.write(reqs)
174
- readme = """
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
- with open("README.md", "w") as f:
183
- f.write(readme)
184
- st.markdown(get_download_link("model.pth", "application/octet-stream"), unsafe_allow_html=True)
185
- st.markdown(get_download_link("app.py", "text/plain"), unsafe_allow_html=True)
186
- st.markdown(get_download_link("requirements.txt", "text/plain"), unsafe_allow_html=True)
187
- st.markdown(get_download_link("README.md", "text/markdown"), unsafe_allow_html=True)
 
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)