Spaces:
Sleeping
Sleeping
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) |