awacke1 commited on
Commit
1c0bc31
Β·
verified Β·
1 Parent(s): 0aec9cd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline
3
+ import os
4
+ import glob
5
+ import re
6
+ import pytz
7
+ from datetime import datetime
8
+ import base64
9
+
10
+ # πŸŒ³πŸ€– AI Knowledge Tree Builder - Growing smarter with every click!
11
+ st.set_page_config(
12
+ page_title="AI Knowledge Tree Builder πŸ“ˆπŸŒΏ",
13
+ page_icon="🌳✨",
14
+ layout="wide",
15
+ initial_sidebar_state="auto",
16
+ )
17
+
18
+ # Predefined Knowledge Trees
19
+ BiologyAndLevel36MagicUsers = """
20
+ 0. Biology Core Rules and Future Exceptions
21
+ 1. Central Dogma DNA RNA Protein
22
+ - Current CRISPR RNA editing πŸ§ͺ
23
+ - Research Gene therapy siRNA πŸ”¬
24
+ - Future Programmable genetics πŸš€
25
+ 2. Cell Origin
26
+ - Current iPSCs organoids 🦠
27
+ - Research Synthetic cells πŸ”¬
28
+ - Future De novo cell creation πŸš€
29
+ """
30
+
31
+ AITopicsToInnovate1 = """
32
+ 1. Major AI Industry Players 🌐
33
+ 1. Research Leaders 🎯
34
+ - OpenAI: GPT-4 DALL-E Foundation Models πŸ”΅
35
+ - Google: PaLM Gemini LLMs 🟦
36
+ - Anthropic: Claude Constitutional AI ⚑
37
+ """
38
+
39
+ MultiplayerGames = """
40
+ 0. Fantasy Domain Introduction
41
+ 1. Setting the Scene
42
+ - Current Create a high-fantasy realm 🏞️
43
+ - Research Add domain-specific entities πŸ§β€β™‚οΈ
44
+ - Future AI-generated worldbuilding πŸš€
45
+ """
46
+
47
+ # Root Node with URLs
48
+ RootNode = """
49
+ 0. Research Hub 🌐
50
+ 1. Awacke1 Profile
51
+ - Link: [Hugging Face Profile](https://huggingface.co/awacke1) πŸ“š
52
+ 2. TeachingCV App
53
+ - Link: [TeachingCV](https://huggingface.co/spaces/awacke1/TeachingCV) πŸ–₯️
54
+ 3. DeepResearchEvaluator App
55
+ - Link: [DeepResearchEvaluator](https://huggingface.co/spaces/awacke1/DeepResearchEvaluator) πŸ”
56
+ """
57
+
58
+ # Utility Functions
59
+ def sanitize_filename(text):
60
+ safe_text = re.sub(r'[^\w\s-]', ' ', text)
61
+ safe_text = re.sub(r'\s+', ' ', safe_text)
62
+ return safe_text.strip()[:50]
63
+
64
+ def generate_timestamp_filename(query):
65
+ central = pytz.timezone('US/Central')
66
+ current_time = datetime.now(central)
67
+ time_str = current_time.strftime("%I%M%p")
68
+ date_str = current_time.strftime("%m%d%Y")
69
+ safe_query = sanitize_filename(query)
70
+ return f"{time_str} {date_str} ({safe_query}).md"
71
+
72
+ def parse_outline_to_mermaid(outline_text):
73
+ lines = outline_text.strip().split('\n')
74
+ nodes = []
75
+ edges = []
76
+ stack = []
77
+ for line in lines:
78
+ indent = len(line) - len(line.lstrip())
79
+ level = indent // 4 # 4 spaces per level
80
+ text = line.strip()
81
+ label = re.sub(r'^[#*\->\d\.\s]+', '', text).strip()
82
+ if label:
83
+ node_id = f"N{len(nodes)}"
84
+ nodes.append(f'{node_id}["{label}"]')
85
+ if stack:
86
+ parent_level = stack[-1][0]
87
+ if level > parent_level:
88
+ parent_id = stack[-1][1]
89
+ edges.append(f"{parent_id} --> {node_id}")
90
+ stack.append((level, node_id))
91
+ else:
92
+ while stack and stack[-1][0] >= level:
93
+ stack.pop()
94
+ if stack:
95
+ parent_id = stack[-1][1]
96
+ edges.append(f"{parent_id} --> {node_id}")
97
+ stack.append((level, node_id))
98
+ else:
99
+ stack.append((level, node_id))
100
+ return "graph TD\n" + "\n".join(nodes + edges)
101
+
102
+ def grow_tree(base_tree, new_node_name, parent_node):
103
+ lines = base_tree.strip().split('\n')
104
+ new_lines = []
105
+ added = False
106
+ for line in lines:
107
+ new_lines.append(line)
108
+ if parent_node in line and not added:
109
+ indent = len(line) - len(line.lstrip())
110
+ new_lines.append(f"{' ' * (indent + 4)}- {new_node_name} 🌱")
111
+ added = True
112
+ return "\n".join(new_lines)
113
+
114
+ def breed_trees(tree1, tree2, intersect_node):
115
+ lines1 = tree1.strip().split('\n')
116
+ lines2 = tree2.strip().split('\n')
117
+ new_lines = lines1.copy()
118
+ for line in lines2:
119
+ if intersect_node not in line and not any(line.strip() in l for l in lines1):
120
+ new_lines.append(line)
121
+ return "\n".join(new_lines)
122
+
123
+ # Model Building Process
124
+ def generate_model_pipeline():
125
+ return """
126
+ graph TD
127
+ A[Load Data πŸ“Š] --> B[Preprocess Data πŸ› οΈ]
128
+ B --> C[Train Model πŸ€–]
129
+ C --> D[Evaluate Model πŸ“ˆ]
130
+ D --> E[Deploy Model πŸš€]
131
+ """
132
+
133
+ # AI Lookup
134
+ @st.cache_resource
135
+ def load_generator():
136
+ return pipeline("text-generation", model="distilgpt2")
137
+
138
+ # Sidebar: File Management
139
+ if 'selected_file' not in st.session_state:
140
+ st.session_state.selected_file = None
141
+
142
+ st.sidebar.title("πŸ“ Saved Interactions")
143
+ md_files = glob.glob("*.md")
144
+ for file in md_files:
145
+ if st.sidebar.button(file):
146
+ st.session_state.selected_file = file
147
+ if st.sidebar.button("Create New Note"):
148
+ filename = generate_timestamp_filename("New Note")
149
+ with open(filename, 'w') as f:
150
+ f.write("# New Note\n")
151
+ st.sidebar.success(f"Created {filename}")
152
+ st.session_state.selected_file = filename
153
+
154
+ # Main App
155
+ st.title("🌳 AI Knowledge Tree Builder 🌱")
156
+ st.markdown("Grow and visualize knowledge trees, build ML pipelines, and explore research!")
157
+
158
+ if st.session_state.selected_file:
159
+ with open(st.session_state.selected_file, 'r') as f:
160
+ content = f.read()
161
+ st.markdown(content)
162
+ else:
163
+ # Knowledge Tree Selection and Growth
164
+ trees = {
165
+ "Research Hub": RootNode,
166
+ "Biology": BiologyAndLevel36MagicUsers,
167
+ "AI Topics": AITopicsToInnovate1,
168
+ "Multiplayer Games": MultiplayerGames
169
+ }
170
+ selected_tree = st.selectbox("Select Knowledge Tree", list(trees.keys()))
171
+ current_tree = trees[selected_tree]
172
+
173
+ # Tree Growth
174
+ new_node = st.text_input("Add New Node (e.g., 'ML Pipeline')")
175
+ parent_node = st.text_input("Parent Node to Attach To (e.g., 'Research Leaders')")
176
+ if st.button("Grow Tree 🌱") and new_node and parent_node:
177
+ current_tree = grow_tree(current_tree, new_node, parent_node)
178
+ trees[selected_tree] = current_tree
179
+ st.success(f"Added '{new_node}' under '{parent_node}'!")
180
+
181
+ # Tree Breeding
182
+ breed_with = st.selectbox("Breed With Another Tree", [t for t in trees.keys() if t != selected_tree])
183
+ intersect_node = st.text_input("Common Node for Breeding (e.g., 'Research')")
184
+ if st.button("Breed Trees 🌳"):
185
+ new_tree = breed_trees(current_tree, trees[breed_with], intersect_node)
186
+ trees[f"{selected_tree} + {breed_with}"] = new_tree
187
+ st.success(f"Created new tree: {selected_tree} + {breed_with}")
188
+
189
+ # Display Tree
190
+ mermaid_code = parse_outline_to_mermaid(current_tree)
191
+ st.markdown("### Knowledge Tree Visualization")
192
+ st.mermaid(mermaid_code)
193
+
194
+ # Model Building Pipeline
195
+ st.markdown("### ML Model Building Pipeline")
196
+ st.mermaid(generate_model_pipeline())
197
+
198
+ # AI Lookup
199
+ query = st.text_input("Enter Query for AI Lookup")
200
+ if st.button("Perform AI Lookup πŸ€–") and query:
201
+ generator = load_generator()
202
+ response = generator(query, max_length=50)[0]['generated_text']
203
+ st.write(f"**AI Response:** {response}")
204
+ filename = generate_timestamp_filename(query)
205
+ with open(filename, 'w') as f:
206
+ f.write(f"# Query: {query}\n\n## AI Response\n{response}")
207
+ st.success(f"Saved to {filename}")
208
+
209
+ if __name__ == "__main__":
210
+ st.sidebar.markdown("Explore, grow, and innovate!")