Harshit0414 commited on
Commit
f3950bb
Β·
verified Β·
1 Parent(s): 6975bef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +242 -0
app.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Frontend Gradio App for RAM-P (PUBLIC)
3
+ This is the public-facing UI that communicates with the private backend via API.
4
+ Deploy this as a PUBLIC Hugging Face Space.
5
+ """
6
+
7
+ import gradio as gr
8
+ import os
9
+ from gradio_client import Client
10
+
11
+ # Get backend URL and token from environment variables
12
+ BACKEND_URL = os.getenv("BACKEND_URL", "") # e.g., "https://username-backend.hf.space"
13
+ HF_TOKEN = os.getenv("HF_TOKEN", "") # Hugging Face token for authentication
14
+
15
+ if not BACKEND_URL:
16
+ raise ValueError("BACKEND_URL environment variable must be set!")
17
+ if not HF_TOKEN:
18
+ raise ValueError("HF_TOKEN environment variable must be set!")
19
+
20
+ # Initialize backend client
21
+ try:
22
+ backend_client = Client(BACKEND_URL, hf_token=HF_TOKEN)
23
+ print(f"Connected to backend at {BACKEND_URL}")
24
+ except Exception as e:
25
+ print(f"Warning: Could not connect to backend: {e}")
26
+ backend_client = None
27
+
28
+ def add_sentences_ui(sentences_text):
29
+ """UI handler for adding sentences."""
30
+ if not backend_client:
31
+ return "❌ Backend not available. Please check configuration.", "**Error:** Backend connection failed."
32
+
33
+ try:
34
+ result = backend_client.predict(
35
+ sentences_text,
36
+ api_name="api_add_sentences"
37
+ )
38
+ if isinstance(result, dict):
39
+ vocab_info = result.get("vocab_info", {})
40
+ vocab_text = f"**Current Vocabulary:** {vocab_info.get('vocab_size', 0)} words\n**Corpus:** {vocab_info.get('corpus_size', 0)} sentences\n**Trained:** {vocab_info.get('trained_size', 0)} sentences"
41
+ return result.get("status", "Unknown status"), vocab_text
42
+ else:
43
+ return str(result), "**Error:** Unexpected response format."
44
+ except Exception as e:
45
+ return f"❌ Error: {str(e)}", "**Error:** Could not connect to backend."
46
+
47
+ def train_brain_ui(epochs, progress=gr.Progress()):
48
+ """UI handler for training."""
49
+ if not backend_client:
50
+ yield "❌ Backend not available. Please check configuration."
51
+ return
52
+
53
+ try:
54
+ yield "πŸ”„ Training in progress... Please wait..."
55
+ result = backend_client.predict(
56
+ int(epochs),
57
+ api_name="api_train"
58
+ )
59
+ if isinstance(result, str):
60
+ yield result
61
+ elif isinstance(result, dict):
62
+ yield result.get("status", "Training completed.")
63
+ else:
64
+ yield str(result)
65
+ except Exception as e:
66
+ yield f"❌ Error: {str(e)}"
67
+
68
+ def run_stream_ui(seed_word, steps, coupling_gain, transmission_threshold):
69
+ """UI handler for stream simulation."""
70
+ if not backend_client:
71
+ return None, "❌ Backend not available. Please check configuration."
72
+
73
+ try:
74
+ result = backend_client.predict(
75
+ seed_word,
76
+ int(steps),
77
+ float(coupling_gain),
78
+ float(transmission_threshold),
79
+ api_name="api_run_stream"
80
+ )
81
+ # Gradio returns tuple/list for multiple outputs
82
+ if isinstance(result, (list, tuple)) and len(result) >= 2:
83
+ return result[0], result[1]
84
+ elif isinstance(result, dict):
85
+ return result.get("image"), result.get("text", "")
86
+ else:
87
+ return None, f"Unexpected response: {result}"
88
+ except Exception as e:
89
+ return None, f"❌ Error: {str(e)}"
90
+
91
+ def clear_brain_ui():
92
+ """UI handler for clearing the brain."""
93
+ if not backend_client:
94
+ return "❌ Backend not available. Please check configuration.", "**Error:** Backend connection failed."
95
+
96
+ try:
97
+ result = backend_client.predict(api_name="api_clear_brain")
98
+ if isinstance(result, dict):
99
+ vocab_info = result.get("vocab_info", {})
100
+ vocab_text = f"**Current Vocabulary:** {vocab_info.get('vocab_size', 0)} words\n**Corpus:** {vocab_info.get('corpus_size', 0)} sentences\n**Trained:** {vocab_info.get('trained_size', 0)} sentences"
101
+ return result.get("status", "Cleared."), vocab_text
102
+ else:
103
+ return str(result), "**Error:** Unexpected response format."
104
+ except Exception as e:
105
+ return f"❌ Error: {str(e)}", "**Error:** Could not connect to backend."
106
+
107
+ # Create Frontend Interface
108
+ with gr.Blocks(title="RAM-P - Interactive Learning") as frontend_app:
109
+ gr.Markdown("""
110
+ # 🧠 RAM-P - Interactive Learning
111
+
112
+ **Start with a blank brain and teach it by adding sentences!**
113
+
114
+ ### How to use:
115
+ 1. **Add Sentences**: Input sentences (one per line) to build vocabulary and corpus
116
+ 2. **Train Brain**: Click "Train Brain" to let it learn associations from your sentences
117
+ 3. **Run Stream**: Enter a seed word and watch the stream of consciousness flow!
118
+ """)
119
+
120
+ with gr.Tabs():
121
+ with gr.Tab("1. Add Sentences"):
122
+ gr.Markdown("### Add sentences to teach the brain")
123
+ gr.Markdown("Enter sentences (one per line). The brain will extract vocabulary from these sentences.")
124
+
125
+ sentences_input = gr.Textbox(
126
+ label="Sentences",
127
+ placeholder="the monkey ate a banana\nprogrammer wrote code\nastronomer saw stars",
128
+ lines=10,
129
+ info="Enter sentences, one per line"
130
+ )
131
+
132
+ add_btn = gr.Button("Add Sentences", variant="primary")
133
+ add_output = gr.Textbox(label="Status", interactive=False)
134
+ vocab_display = gr.Markdown(label="Vocabulary Info")
135
+
136
+ add_btn.click(
137
+ fn=add_sentences_ui,
138
+ inputs=sentences_input,
139
+ outputs=[add_output, vocab_display]
140
+ )
141
+
142
+ with gr.Tab("2. Train Brain"):
143
+ gr.Markdown("### Train the brain on your corpus")
144
+ gr.Markdown("The brain will learn associations between words that appear together in sentences. **Incremental learning**: Adding new sentences expands the brain without losing previous knowledge.")
145
+
146
+ with gr.Row():
147
+ with gr.Column(scale=2):
148
+ epochs_slider = gr.Slider(
149
+ label="Training Epochs",
150
+ minimum=1,
151
+ maximum=10,
152
+ value=2,
153
+ step=1,
154
+ info="Number of times to go through the corpus"
155
+ )
156
+
157
+ train_btn = gr.Button("Train Brain", variant="primary", size="lg")
158
+ train_output = gr.Markdown(label="Training Status", value="Ready to train. Click 'Train Brain' to start.")
159
+
160
+ train_btn.click(
161
+ fn=train_brain_ui,
162
+ inputs=epochs_slider,
163
+ outputs=train_output
164
+ )
165
+
166
+ with gr.Column(scale=1):
167
+ gr.Markdown("### Brain Management")
168
+ clear_btn = gr.Button("Clear Brain", variant="stop", size="lg")
169
+ clear_output = gr.Markdown(label="Clear Status")
170
+ clear_vocab_display = gr.Markdown(label="Vocabulary Info")
171
+
172
+ clear_btn.click(
173
+ fn=clear_brain_ui,
174
+ inputs=None,
175
+ outputs=[clear_output, clear_vocab_display]
176
+ )
177
+
178
+ with gr.Tab("3. Stream of Consciousness"):
179
+ gr.Markdown("### Run stream of consciousness simulation")
180
+ gr.Markdown("Enter a seed word and watch how the brain's thoughts flow and associate.")
181
+
182
+ with gr.Row():
183
+ with gr.Column(scale=1):
184
+ seed_word_input = gr.Textbox(
185
+ label="Seed Word",
186
+ value="",
187
+ placeholder="Enter a word from your vocabulary...",
188
+ info="The initial concept to inject"
189
+ )
190
+
191
+ steps_slider = gr.Slider(
192
+ label="Simulation Steps",
193
+ minimum=100,
194
+ maximum=1000,
195
+ value=400,
196
+ step=50
197
+ )
198
+
199
+ coupling_slider = gr.Slider(
200
+ label="Coupling Gain",
201
+ minimum=0.0,
202
+ maximum=200.0,
203
+ value=80.0,
204
+ step=5.0,
205
+ info="How strongly thoughts pull on each other"
206
+ )
207
+
208
+ threshold_slider = gr.Slider(
209
+ label="Transmission Threshold",
210
+ minimum=0.01,
211
+ maximum=0.5,
212
+ value=0.05,
213
+ step=0.01,
214
+ info="Minimum activation for influence"
215
+ )
216
+
217
+ stream_btn = gr.Button("Run Stream", variant="primary", size="lg")
218
+
219
+ with gr.Column(scale=2):
220
+ stream_image = gr.Image(
221
+ label="Stream of Consciousness Visualization",
222
+ type="filepath"
223
+ )
224
+ stream_text = gr.Markdown(label="Narrative Chain")
225
+
226
+ stream_btn.click(
227
+ fn=run_stream_ui,
228
+ inputs=[seed_word_input, steps_slider, coupling_slider, threshold_slider],
229
+ outputs=[stream_image, stream_text]
230
+ )
231
+
232
+ gr.Markdown("""
233
+ ---
234
+ **Tips:**
235
+ - Add diverse sentences to build a rich vocabulary
236
+ - More training epochs = stronger associations
237
+ - Try different seed words to see different thought patterns
238
+ """)
239
+
240
+ if __name__ == "__main__":
241
+ frontend_app.launch(server_name="0.0.0.0", server_port=7861)
242
+