File size: 4,462 Bytes
bd035eb
 
 
 
d6985e9
6dd5d74
d6985e9
aac343a
d6985e9
6dd5d74
 
d6985e9
aac343a
d6985e9
 
 
 
 
 
 
 
6dd5d74
d6985e9
 
aac343a
d6985e9
6dd5d74
d6985e9
 
6dd5d74
d6985e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dd5d74
d6985e9
bd035eb
 
d6985e9
 
 
6dd5d74
bd035eb
d6985e9
 
 
 
 
 
 
6dd5d74
d6985e9
 
 
6dd5d74
bd035eb
6dd5d74
d6985e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd035eb
d6985e9
 
 
 
 
 
 
 
 
 
 
bd035eb
 
d6985e9
6dd5d74
bd035eb
d6985e9
 
 
 
 
 
 
 
bd035eb
 
d6985e9
 
 
 
 
 
 
 
 
 
 
 
bd035eb
d6985e9
 
 
 
 
 
 
 
 
 
bd035eb
 
d6985e9
bd035eb
d6985e9
bd035eb
 
d6985e9
6dd5d74
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import gradio as gr
import torch
import numpy as np
import plotly.graph_objects as go
from huggingface_hub import snapshot_download
from pathlib import Path
import sys

# 1. Setup Model dari Hugging Face Hub ----------------------------
def setup_model():
    REPO_ID = "VLabTech/cognitive_net"
    LOCAL_DIR = "cognitive_net_pkg"
    
    # Download repo
    snapshot_download(
        repo_id=REPO_ID,
        local_dir=LOCAL_DIR,
        allow_patterns=["*.py", "*.txt"],
        repo_type="model",
        local_dir_use_symlinks=False
    )
    
    # Tambahkan ke path Python
    sys.path.insert(0, str(Path(LOCAL_DIR).absolute()))

setup_model()

# 2. Implementasi Model --------------------------------------------
from cognitive_net.network import DynamicCognitiveNet

class CognitiveDemo:
    def __init__(self):
        self.net = DynamicCognitiveNet(input_size=5, output_size=1)
        self.training_loss = []
        self.emotion_states = []
    
    def _parse_input(self, sequence_str):
        """Konversi string input ke tensor"""
        sequence = [float(x.strip()) for x in sequence_str.split(',')]
        if len(sequence) < 6:
            raise ValueError("Input minimal 6 angka")
        return (
            torch.tensor(sequence[:-1]).float(),
            torch.tensor([sequence[-1]]).float()
        )
    
    def train(self, sequence_str, epochs):
        try:
            X, y = self._parse_input(sequence_str)
            
            # Training loop
            self.training_loss = []
            self.emotion_states = []
            
            for _ in range(epochs):
                loss = self.net.train_step(X, y)
                self.training_loss.append(loss)
                self.emotion_states.append(self.net.emotional_state.item())
            
            # Prediksi akhir
            with torch.no_grad():
                pred = self.net(X)
            
            return {
                "prediction": f"{pred.item():.4f}",
                "loss_plot": self._create_loss_plot(),
                "emotion_plot": self._create_emotion_plot()
            }
        except Exception as e:
            return {"error": str(e)}
    
    def _create_loss_plot(self):
        fig = go.Figure()
        fig.add_trace(go.Scatter(
            y=self.training_loss,
            mode='lines+markers',
            name='Loss'
        ))
        fig.update_layout(
            title='Training Loss',
            xaxis_title='Epoch',
            yaxis_title='Loss Value'
        )
        return fig
    
    def _create_emotion_plot(self):
        fig = go.Figure()
        fig.add_trace(go.Scatter(
            y=self.emotion_states,
            mode='lines',
            name='Emotional State',
            line=dict(color='#FF6F61')
        ))
        fig.update_layout(
            title='Emotional State Dynamics',
            xaxis_title='Epoch',
            yaxis_title='State Value'
        )
        return fig

# 3. Antarmuka Gradio ----------------------------------------------
demo = CognitiveDemo()

with gr.Blocks(theme=gr.themes.Soft(), title="Cognitive Network Demo") as app:
    gr.Markdown("# 🧠 Cognitive Network Demo")
    gr.Markdown("""
    **Demonstrasi Jaringan Saraf Kognitif dengan:**
    - Memori Adaptif
    - Plastisitas Struktural
    - Modulasi Emosional
    """)
    
    with gr.Row():
        with gr.Column():
            input_seq = gr.Textbox(
                label="Deret Input (contoh: 0.1, 0.3, 0.5, 0.7, 0.9, 1.1)",
                value="0.1, 0.3, 0.5, 0.7, 0.9, 1.1"
            )
            epochs = gr.Slider(10, 500, value=100, label="Jumlah Epoch")
            train_btn = gr.Button("🚀 Latih Model", variant="primary")
        
        with gr.Column():
            output_pred = gr.Label(label="Prediksi")
            loss_plot = gr.Plot(label="Progress Training")
            emotion_plot = gr.Plot(label="Dinamika Emosional")
    
    # Contoh data preset
    gr.Examples(
        examples=[
            ["1, 2, 3, 4, 5, 6", 100],
            ["0.5, 1.0, 1.5, 2.0, 2.5, 3.0", 150],
            ["10, 8, 6, 4, 2, 0", 200]
        ],
        inputs=[input_seq, epochs],
        label="Contoh Input"
    )
    
    train_btn.click(
        fn=demo.train,
        inputs=[input_seq, epochs],
        outputs=[output_pred, loss_plot, emotion_plot]
    )

# 4. Jalankan Aplikasi ---------------------------------------------
if __name__ == "__main__":
    app.launch(debug=True)