vincentiusyoshuac commited on
Commit
6a2403a
·
verified ·
1 Parent(s): d6985e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -129
app.py CHANGED
@@ -1,146 +1,93 @@
1
- import gradio as gr
 
2
  import torch
3
- import numpy as np
4
- import plotly.graph_objects as go
5
- from huggingface_hub import snapshot_download
6
- from pathlib import Path
7
- import sys
8
-
9
- # 1. Setup Model dari Hugging Face Hub ----------------------------
10
- def setup_model():
11
- REPO_ID = "VLabTech/cognitive_net"
12
- LOCAL_DIR = "cognitive_net_pkg"
13
-
14
- # Download repo
15
- snapshot_download(
16
- repo_id=REPO_ID,
17
- local_dir=LOCAL_DIR,
18
- allow_patterns=["*.py", "*.txt"],
19
- repo_type="model",
20
- local_dir_use_symlinks=False
21
- )
22
-
23
- # Tambahkan ke path Python
24
- sys.path.insert(0, str(Path(LOCAL_DIR).absolute()))
25
-
26
- setup_model()
27
-
28
- # 2. Implementasi Model --------------------------------------------
29
- from cognitive_net.network import DynamicCognitiveNet
30
 
31
- class CognitiveDemo:
32
  def __init__(self):
33
- self.net = DynamicCognitiveNet(input_size=5, output_size=1)
34
- self.training_loss = []
35
- self.emotion_states = []
36
-
37
- def _parse_input(self, sequence_str):
38
- """Konversi string input ke tensor"""
39
- sequence = [float(x.strip()) for x in sequence_str.split(',')]
40
- if len(sequence) < 6:
41
- raise ValueError("Input minimal 6 angka")
42
- return (
43
- torch.tensor(sequence[:-1]).float(),
44
- torch.tensor([sequence[-1]]).float()
45
- )
46
-
47
- def train(self, sequence_str, epochs):
48
  try:
49
- X, y = self._parse_input(sequence_str)
 
50
 
51
- # Training loop
52
- self.training_loss = []
53
- self.emotion_states = []
 
 
54
 
55
- for _ in range(epochs):
56
- loss = self.net.train_step(X, y)
57
- self.training_loss.append(loss)
58
- self.emotion_states.append(self.net.emotional_state.item())
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Prediksi akhir
 
 
 
61
  with torch.no_grad():
62
- pred = self.net(X)
 
 
 
 
 
63
 
64
- return {
65
- "prediction": f"{pred.item():.4f}",
66
- "loss_plot": self._create_loss_plot(),
67
- "emotion_plot": self._create_emotion_plot()
68
- }
69
  except Exception as e:
70
- return {"error": str(e)}
71
-
72
- def _create_loss_plot(self):
73
- fig = go.Figure()
74
- fig.add_trace(go.Scatter(
75
- y=self.training_loss,
76
- mode='lines+markers',
77
- name='Loss'
78
- ))
79
- fig.update_layout(
80
- title='Training Loss',
81
- xaxis_title='Epoch',
82
- yaxis_title='Loss Value'
83
- )
84
- return fig
85
-
86
- def _create_emotion_plot(self):
87
- fig = go.Figure()
88
- fig.add_trace(go.Scatter(
89
- y=self.emotion_states,
90
- mode='lines',
91
- name='Emotional State',
92
- line=dict(color='#FF6F61')
93
- ))
94
- fig.update_layout(
95
- title='Emotional State Dynamics',
96
- xaxis_title='Epoch',
97
- yaxis_title='State Value'
98
- )
99
- return fig
100
 
101
- # 3. Antarmuka Gradio ----------------------------------------------
102
- demo = CognitiveDemo()
103
 
104
- with gr.Blocks(theme=gr.themes.Soft(), title="Cognitive Network Demo") as app:
105
- gr.Markdown("# 🧠 Cognitive Network Demo")
106
- gr.Markdown("""
107
- **Demonstrasi Jaringan Saraf Kognitif dengan:**
108
- - Memori Adaptif
109
- - Plastisitas Struktural
110
- - Modulasi Emosional
111
- """)
 
 
 
112
 
113
- with gr.Row():
114
- with gr.Column():
115
- input_seq = gr.Textbox(
116
- label="Deret Input (contoh: 0.1, 0.3, 0.5, 0.7, 0.9, 1.1)",
117
- value="0.1, 0.3, 0.5, 0.7, 0.9, 1.1"
118
- )
119
- epochs = gr.Slider(10, 500, value=100, label="Jumlah Epoch")
120
- train_btn = gr.Button("🚀 Latih Model", variant="primary")
121
-
122
- with gr.Column():
123
- output_pred = gr.Label(label="Prediksi")
124
- loss_plot = gr.Plot(label="Progress Training")
125
- emotion_plot = gr.Plot(label="Dinamika Emosional")
126
 
127
- # Contoh data preset
128
- gr.Examples(
129
- examples=[
130
- ["1, 2, 3, 4, 5, 6", 100],
131
- ["0.5, 1.0, 1.5, 2.0, 2.5, 3.0", 150],
132
- ["10, 8, 6, 4, 2, 0", 200]
133
- ],
134
- inputs=[input_seq, epochs],
135
- label="Contoh Input"
136
- )
137
 
138
- train_btn.click(
139
- fn=demo.train,
140
- inputs=[input_seq, epochs],
141
- outputs=[output_pred, loss_plot, emotion_plot]
142
- )
 
 
 
 
 
 
143
 
144
- # 4. Jalankan Aplikasi ---------------------------------------------
145
  if __name__ == "__main__":
146
- app.launch(debug=True)
 
1
+ # app.py
2
+ import os
3
  import torch
4
+ import gradio as gr
5
+ from huggingface_hub import hf_hub_download
6
+ from cognitive_net import DynamicCognitiveNet, CognitiveMemory, CognitiveNode
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ class ModelInterface:
9
  def __init__(self):
10
+ self.model = self.load_model()
11
+
12
+ def load_model(self):
13
+ """Load model dari HuggingFace Hub"""
 
 
 
 
 
 
 
 
 
 
 
14
  try:
15
+ # Inisialisasi model
16
+ model = DynamicCognitiveNet(input_size=5, output_size=2)
17
 
18
+ # Download checkpoint
19
+ checkpoint_path = hf_hub_download(
20
+ repo_id="VLabTech/cognitive_net",
21
+ filename="model.pt"
22
+ )
23
 
24
+ # Load weights
25
+ model.load_state_dict(torch.load(checkpoint_path))
26
+ model.eval()
27
+ return model
28
+ except Exception as e:
29
+ print(f"Error loading model: {e}")
30
+ return None
31
+
32
+ def predict(self, input_text):
33
+ """Proses input dan generate prediksi"""
34
+ try:
35
+ # Parse input
36
+ values = [float(x.strip()) for x in input_text.split(",")]
37
+ if len(values) != 5:
38
+ return f"Error: Masukkan tepat 5 nilai (dipisahkan koma). Anda memasukkan {len(values)} nilai."
39
 
40
+ # Convert ke tensor
41
+ input_tensor = torch.tensor(values, dtype=torch.float32)
42
+
43
+ # Generate prediksi
44
  with torch.no_grad():
45
+ output = self.model(input_tensor)
46
+
47
+ # Format output
48
+ result = f"Hasil Prediksi:\n"
49
+ result += f"Output 1: {output[0]:.4f}\n"
50
+ result += f"Output 2: {output[1]:.4f}"
51
 
52
+ return result
53
+
54
+ except ValueError:
55
+ return "Error: Pastikan semua input adalah angka valid"
 
56
  except Exception as e:
57
+ return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # Inisialisasi interface
60
+ model_interface = ModelInterface()
61
 
62
+ # Setup Gradio Interface
63
+ demo = gr.Interface(
64
+ fn=model_interface.predict,
65
+ inputs=gr.Textbox(
66
+ label="Input Values",
67
+ placeholder="Masukkan 5 nilai numerik (pisahkan dengan koma). Contoh: 1.0, 2.0, 3.0, 4.0, 5.0"
68
+ ),
69
+ outputs=gr.Textbox(label="Hasil Prediksi"),
70
+ title="Cognitive Network Demo",
71
+ description="""
72
+ ## Cognitive Network Inference Demo
73
 
74
+ Model ini menerima 5 input numerik dan menghasilkan 2 output numerik.
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ ### Cara Penggunaan:
77
+ 1. Masukkan 5 angka yang dipisahkan dengan koma
78
+ 2. Klik Submit untuk melihat hasil prediksi
 
 
 
 
 
 
 
79
 
80
+ ### Format Input:
81
+ - Masukkan tepat 5 nilai numerik
82
+ - Pisahkan nilai dengan koma
83
+ - Gunakan titik untuk desimal
84
+ """,
85
+ examples=[
86
+ ["1.0, 2.0, 3.0, 4.0, 5.0"],
87
+ ["0.5, -1.0, 2.5, 1.5, -0.5"],
88
+ ["0.1, 0.2, 0.3, 0.4, 0.5"]
89
+ ]
90
+ )
91
 
 
92
  if __name__ == "__main__":
93
+ demo.launch()