Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,159 +3,118 @@ import torch
|
|
3 |
import numpy as np
|
4 |
import plotly.graph_objects as go
|
5 |
from huggingface_hub import hf_hub_download
|
6 |
-
from pathlib import Path
|
7 |
import sys
|
8 |
import os
|
|
|
9 |
|
10 |
-
# Download
|
11 |
-
def
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
|
|
|
16 |
model_dir.mkdir(exist_ok=True)
|
17 |
|
18 |
-
|
|
|
19 |
try:
|
20 |
-
hf_hub_download(
|
21 |
-
repo_id=
|
22 |
filename=file,
|
23 |
-
local_dir=model_dir
|
|
|
24 |
)
|
25 |
except Exception as e:
|
26 |
print(f"Error downloading {file}: {str(e)}")
|
27 |
-
|
28 |
-
# Add
|
29 |
if str(model_dir.absolute()) not in sys.path:
|
30 |
-
sys.path.
|
31 |
|
32 |
-
#
|
33 |
-
|
34 |
-
|
35 |
-
# Now import the model
|
36 |
-
try:
|
37 |
-
from cognitive_net import DynamicCognitiveNet
|
38 |
-
except ImportError as e:
|
39 |
-
print(f"Error importing model: {str(e)}")
|
40 |
-
raise
|
41 |
-
|
42 |
-
class ModelDemo:
|
43 |
def __init__(self):
|
44 |
-
|
45 |
-
self.training_history = []
|
46 |
-
self.emotional_history = []
|
47 |
|
48 |
-
def train_sequence(self, sequence_str, epochs):
|
49 |
-
"""Train model on input sequence and return visualizations"""
|
50 |
try:
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
59 |
|
60 |
# Training loop
|
61 |
losses = []
|
62 |
-
|
63 |
-
for epoch in range(epochs):
|
64 |
loss = self.net.train_step(X, y)
|
65 |
losses.append(loss)
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
xaxis_title='Epoch',
|
73 |
-
yaxis_title='Loss')
|
74 |
-
|
75 |
-
# Create emotion plot
|
76 |
-
emotion_fig = go.Figure()
|
77 |
-
emotion_fig.add_trace(go.Scatter(y=emotions, name='Emotional State'))
|
78 |
-
emotion_fig.update_layout(title='Emotional State',
|
79 |
-
xaxis_title='Epoch',
|
80 |
-
yaxis_title='Value')
|
81 |
-
|
82 |
-
# Make prediction
|
83 |
-
with torch.no_grad():
|
84 |
-
pred = self.net(X)
|
85 |
-
result = f"Prediction: {pred.item():.4f} (Target: {y.item():.4f})"
|
86 |
-
|
87 |
-
return result, loss_fig, emotion_fig
|
88 |
|
89 |
except Exception as e:
|
90 |
-
return
|
91 |
-
|
92 |
-
def
|
93 |
-
"""Visualize memory importance weights"""
|
94 |
-
memories = []
|
95 |
-
importances = []
|
96 |
-
|
97 |
-
for mem in self.net.nodes['input_0'].memory.memory_queue:
|
98 |
-
memories.append(mem['context'].numpy())
|
99 |
-
importances.append(mem['importance'].item())
|
100 |
-
|
101 |
-
if not memories:
|
102 |
-
return "No memories stored yet"
|
103 |
-
|
104 |
fig = go.Figure()
|
105 |
-
fig.add_trace(go.
|
106 |
-
fig.update_layout(title=
|
107 |
-
xaxis_title='Memory Index',
|
108 |
-
yaxis_title='Importance')
|
109 |
return fig
|
110 |
|
111 |
-
#
|
112 |
-
demo =
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
gr.Markdown("""
|
117 |
-
# Cognitive Network Interactive Demo
|
118 |
-
|
119 |
-
This demo shows a neural network with:
|
120 |
-
- Dynamic memories
|
121 |
-
- Emotional modulation
|
122 |
-
- Adaptive structure
|
123 |
-
|
124 |
-
Enter a sequence of numbers (comma-separated) to train the model to predict the next number.
|
125 |
-
|
126 |
-
Model: [VLabTech/cognitive_net](https://huggingface.co/VLabTech/cognitive_net)
|
127 |
-
""")
|
128 |
|
129 |
with gr.Row():
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
epochs = gr.Slider(minimum=10, maximum=500, value=100,
|
134 |
-
step=10, label="Training Epochs")
|
135 |
-
train_btn = gr.Button("Train Model")
|
136 |
-
|
137 |
-
result_text = gr.Textbox(label="Prediction Result")
|
138 |
|
139 |
with gr.Row():
|
140 |
-
|
141 |
-
|
|
|
142 |
|
143 |
-
|
144 |
-
memory_btn = gr.Button("Visualize Memory")
|
145 |
-
memory_plot = gr.Plot(label="Memory Importance")
|
146 |
|
147 |
-
# Connect components
|
148 |
train_btn.click(
|
149 |
-
fn=demo.
|
150 |
inputs=[input_seq, epochs],
|
151 |
-
outputs=[
|
152 |
-
)
|
153 |
-
|
154 |
-
memory_btn.click(
|
155 |
-
fn=demo.visualize_memory,
|
156 |
-
inputs=None,
|
157 |
-
outputs=memory_plot
|
158 |
)
|
159 |
|
160 |
-
#
|
161 |
-
|
|
|
|
3 |
import numpy as np
|
4 |
import plotly.graph_objects as go
|
5 |
from huggingface_hub import hf_hub_download
|
|
|
6 |
import sys
|
7 |
import os
|
8 |
+
from pathlib import Path
|
9 |
|
10 |
+
# 1. Download Model Files ------------------------------------------------
|
11 |
+
def setup_model():
|
12 |
+
REPO_ID = "VLabTech/cognitive_net"
|
13 |
+
FILE_LIST = [
|
14 |
+
"cognitive_net/__init__.py",
|
15 |
+
"cognitive_net/memory.py",
|
16 |
+
"cognitive_net/node.py",
|
17 |
+
"cognitive_net/network.py"
|
18 |
+
]
|
19 |
|
20 |
+
# Create package directory
|
21 |
+
model_dir = Path("cognitive_net")
|
22 |
model_dir.mkdir(exist_ok=True)
|
23 |
|
24 |
+
# Download files
|
25 |
+
for file in FILE_LIST:
|
26 |
try:
|
27 |
+
downloaded_file = hf_hub_download(
|
28 |
+
repo_id=REPO_ID,
|
29 |
filename=file,
|
30 |
+
local_dir=model_dir.parent,
|
31 |
+
force_filename=file
|
32 |
)
|
33 |
except Exception as e:
|
34 |
print(f"Error downloading {file}: {str(e)}")
|
35 |
+
|
36 |
+
# Add to Python path
|
37 |
if str(model_dir.absolute()) not in sys.path:
|
38 |
+
sys.path.insert(0, str(model_dir.absolute()))
|
39 |
|
40 |
+
# 2. Initialize Model ----------------------------------------------------
|
41 |
+
class CognitiveDemo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
def __init__(self):
|
43 |
+
setup_model()
|
|
|
|
|
44 |
|
|
|
|
|
45 |
try:
|
46 |
+
from cognitive_net import DynamicCognitiveNet
|
47 |
+
self.net = DynamicCognitiveNet(input_size=5, output_size=1)
|
48 |
+
self.net.optimizer = torch.optim.AdamW(self.net.parameters(), lr=0.001)
|
49 |
+
except ImportError as e:
|
50 |
+
raise RuntimeError(f"Gagal memuat model: {str(e)}")
|
51 |
+
|
52 |
+
self.training_history = []
|
53 |
+
|
54 |
+
def _adapt_model(self, X: torch.Tensor, y: torch.Tensor):
|
55 |
+
"""Penyesuaian dimensi tensor untuk arsitektur kognitif"""
|
56 |
+
X = X.view(-1, 1) # Bentuk (seq_len, 1)
|
57 |
+
y = y.view(1) # Bentuk (1,)
|
58 |
+
return X, y
|
59 |
+
|
60 |
+
def train(self, sequence: str, epochs: int):
|
61 |
+
try:
|
62 |
+
# Parse dan validasi input
|
63 |
+
nums = [float(n.strip()) for n in sequence.split(',')]
|
64 |
+
if len(nums) < 6:
|
65 |
+
raise ValueError("Input minimal 6 angka")
|
66 |
|
67 |
+
X = torch.tensor(nums[:-1])
|
68 |
+
y = torch.tensor([nums[-1]])
|
69 |
+
|
70 |
+
# Adaptasi dimensi
|
71 |
+
X, y = self._adapt_model(X, y)
|
72 |
|
73 |
# Training loop
|
74 |
losses = []
|
75 |
+
for _ in range(epochs):
|
|
|
76 |
loss = self.net.train_step(X, y)
|
77 |
losses.append(loss)
|
78 |
+
|
79 |
+
return {
|
80 |
+
"prediction": self.net(X).detach().numpy()[0],
|
81 |
+
"loss_plot": self._create_plot(losses, "Loss Training"),
|
82 |
+
"emotion": self.net.emotional_state.item()
|
83 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
except Exception as e:
|
86 |
+
return {"error": str(e)}
|
87 |
+
|
88 |
+
def _create_plot(self, data, title):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
fig = go.Figure()
|
90 |
+
fig.add_trace(go.Scatter(y=data, mode='lines'))
|
91 |
+
fig.update_layout(title=title)
|
|
|
|
|
92 |
return fig
|
93 |
|
94 |
+
# 3. Gradio Interface ----------------------------------------------------
|
95 |
+
demo = CognitiveDemo()
|
96 |
|
97 |
+
with gr.Blocks(title="Cognitive Network Demo") as app:
|
98 |
+
gr.Markdown("""## Demo Jaringan Kognitif VLabTech""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
with gr.Row():
|
101 |
+
input_seq = gr.Textbox(label="Deret Input (contoh: 0.1, 0.5, 1.0,...)",
|
102 |
+
value="0.1, 0.3, 0.5, 0.7, 0.9, 1.1")
|
103 |
+
epochs = gr.Slider(10, 500, value=100, label="Jumlah Epoch")
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
with gr.Row():
|
106 |
+
train_btn = gr.Button("🚀 Latih Model")
|
107 |
+
pred_output = gr.Label(label="Hasil Prediksi")
|
108 |
+
emotion_output = gr.Number(label="Status Emosional")
|
109 |
|
110 |
+
loss_plot = gr.Plot(label="Progress Training")
|
|
|
|
|
111 |
|
|
|
112 |
train_btn.click(
|
113 |
+
fn=lambda s, e: demo.train(s, e),
|
114 |
inputs=[input_seq, epochs],
|
115 |
+
outputs=[pred_output, loss_plot, emotion_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
)
|
117 |
|
118 |
+
# 4. Run App -------------------------------------------------------------
|
119 |
+
if __name__ == "__main__":
|
120 |
+
app.launch(debug=True)
|