vincentiusyoshuac commited on
Commit
5b766e8
·
verified ·
1 Parent(s): 57b5789

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -141
app.py CHANGED
@@ -2,155 +2,82 @@ import os
2
  import sys
3
  import torch
4
  import gradio as gr
5
- import importlib
6
  from huggingface_hub import hf_hub_download, snapshot_download
7
- from typing import List, Union
8
- from pathlib import Path
9
 
10
- class CognitiveNetApp:
11
- def __init__(self):
12
- self.model = None
13
- self.model_class = None
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- def setup_environment(self) -> None:
16
- """
17
- Menyiapkan environment untuk cognitive_net.
18
- Mendownload repository dan mengatur Python path.
19
- """
20
- repo_path = snapshot_download(repo_id="VLabTech/cognitive_net")
21
- repo_path = Path(repo_path)
22
 
23
- if str(repo_path) not in sys.path:
24
- sys.path.insert(0, str(repo_path))
25
-
26
- # Tambahkan parent directory juga ke Python path
27
- parent_path = str(repo_path.parent)
28
- if parent_path not in sys.path:
29
- sys.path.insert(0, parent_path)
30
-
31
- def load_model(self) -> None:
32
- """
33
- Memuat model cognitive_net dan checkpoint-nya.
34
- Raises:
35
- ImportError: Jika modul tidak dapat diimport
36
- RuntimeError: Jika terjadi kesalahan saat memuat model
37
- """
38
- try:
39
- self.setup_environment()
40
-
41
- import cognitive_net
42
- importlib.reload(cognitive_net)
43
- from cognitive_net.network import DynamicCognitiveNet
44
-
45
- self.model_class = DynamicCognitiveNet
46
- self.model = DynamicCognitiveNet(input_size=5, output_size=2)
47
-
48
- # Muat weights
49
- checkpoint_path = hf_hub_download(
50
- repo_id="VLabTech/cognitive_net",
51
- filename="model.pt"
52
- )
53
- self.model.load_state_dict(torch.load(checkpoint_path))
54
- self.model.eval()
55
-
56
- except ImportError as e:
57
- raise ImportError(f"Gagal mengimport cognitive_net: {str(e)}")
58
- except Exception as e:
59
- raise RuntimeError(f"Gagal memuat model: {str(e)}")
60
-
61
- def parse_input(self, input_text: str) -> List[float]:
62
- """
63
- Mengurai input text menjadi list of floats.
64
 
65
- Args:
66
- input_text: String berisi angka yang dipisahkan koma
67
-
68
- Returns:
69
- List of float values
70
-
71
- Raises:
72
- ValueError: Jika format input tidak valid
73
- """
74
- try:
75
- values = [float(x.strip()) for x in input_text.split(",")]
76
- if len(values) != 5:
77
- raise ValueError(
78
- f"Dibutuhkan tepat 5 nilai (dipisahkan koma). "
79
- f"Anda memasukkan {len(values)} nilai."
80
- )
81
- return values
82
- except ValueError as e:
83
- raise ValueError(f"Format input tidak valid: {str(e)}")
84
-
85
- def predict(self, input_text: str) -> str:
86
- """
87
- Memproses input dan menghasilkan prediksi.
88
 
89
- Args:
90
- input_text: String berisi 5 angka yang dipisahkan koma
91
-
92
- Returns:
93
- String berisi hasil prediksi atau pesan error
94
- """
95
- try:
96
- if self.model is None:
97
- self.load_model()
98
-
99
- # Parse input
100
- values = self.parse_input(input_text)
101
-
102
- # Generate prediction
103
- input_tensor = torch.tensor(values, dtype=torch.float32)
104
- with torch.no_grad():
105
- output = self.model(input_tensor)
106
-
107
- # Format output
108
- result = "Hasil Prediksi:\n"
109
- result += f"Output 1: {output[0]:.4f}\n"
110
- result += f"Output 2: {output[1]:.4f}"
111
-
112
- return result
113
-
114
- except ValueError as e:
115
- return f"Error: {str(e)}"
116
- except Exception as e:
117
- return f"Error: {str(e)}\nTrace: {e.__traceback__}"
118
-
119
- def create_demo() -> gr.Interface:
120
- """
121
- Membuat dan mengkonfigurasi Gradio interface.
122
-
123
- Returns:
124
- Gradio Interface object
125
- """
126
- app = CognitiveNetApp()
127
-
128
- demo = gr.Interface(
129
- fn=app.predict,
130
- inputs=gr.Textbox(
131
- label="Input Values",
132
- placeholder="Masukkan 5 nilai numerik (pisahkan dengan koma). "
133
- "Contoh: 1.0, 2.0, 3.0, 4.0, 5.0"
134
- ),
135
- outputs=gr.Textbox(label="Hasil Prediksi"),
136
- title="Cognitive Network Demo",
137
- description="""
138
- ## Cognitive Network Inference Demo
139
 
140
- Model ini menerima 5 input numerik dan menghasilkan 2 output numerik menggunakan
141
- arsitektur Cognitive Network yang terinspirasi dari cara kerja otak biologis.
 
 
142
 
143
- Model source: https://huggingface.co/VLabTech/cognitive_net
144
- """,
145
- examples=[
146
- ["1.0, 2.0, 3.0, 4.0, 5.0"],
147
- ["0.5, -1.0, 2.5, 1.5, -0.5"],
148
- ["0.1, 0.2, 0.3, 0.4, 0.5"]
149
- ]
150
- )
151
-
152
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  if __name__ == "__main__":
155
- demo = create_demo()
156
  demo.launch()
 
2
  import sys
3
  import torch
4
  import gradio as gr
 
5
  from huggingface_hub import hf_hub_download, snapshot_download
 
 
6
 
7
+ def predict(input_text: str) -> str:
8
+ """
9
+ Memproses input dan menghasilkan prediksi
10
+ """
11
+ try:
12
+ # Parse input
13
+ values = [float(x.strip()) for x in input_text.split(",")]
14
+ if len(values) != 5:
15
+ return f"Error: Masukkan tepat 5 nilai (dipisahkan koma). Anda memasukkan {len(values)} nilai."
16
+
17
+ # Download dan load kode model
18
+ repo_path = snapshot_download(
19
+ repo_id="VLabTech/cognitive_net",
20
+ local_dir="./model_repo"
21
+ )
22
 
23
+ # Import files secara langsung
24
+ import sys
25
+ sys.path.append("./model_repo")
 
 
 
 
26
 
27
+ # Import komponen model
28
+ from memory import CognitiveMemory
29
+ from node import CognitiveNode
30
+ from network import DynamicCognitiveNet
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ # Setup model
33
+ model = DynamicCognitiveNet(input_size=5, output_size=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # Load weights
36
+ checkpoint_path = hf_hub_download(
37
+ repo_id="VLabTech/cognitive_net",
38
+ filename="model.pt",
39
+ local_dir="./model_weights"
40
+ )
41
+ model.load_state_dict(torch.load(checkpoint_path))
42
+ model.eval()
43
+
44
+ # Generate prediction
45
+ input_tensor = torch.tensor(values, dtype=torch.float32)
46
+ with torch.no_grad():
47
+ output = model(input_tensor)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Format output
50
+ result = "Hasil Prediksi:\n"
51
+ result += f"Output 1: {output[0]:.4f}\n"
52
+ result += f"Output 2: {output[1]:.4f}"
53
 
54
+ return result
55
+
56
+ except ValueError as e:
57
+ return f"Error dalam format input: {str(e)}"
58
+ except Exception as e:
59
+ return f"Error: {str(e)}"
60
+
61
+ # Setup Gradio Interface
62
+ demo = gr.Interface(
63
+ fn=predict,
64
+ inputs=gr.Textbox(
65
+ label="Input Values",
66
+ placeholder="Masukkan 5 nilai numerik (pisahkan dengan koma). Contoh: 1.0, 2.0, 3.0, 4.0, 5.0"
67
+ ),
68
+ outputs=gr.Textbox(label="Hasil Prediksi"),
69
+ title="Cognitive Network Demo",
70
+ description="""
71
+ ## Cognitive Network Inference Demo
72
+ Model ini menerima 5 input numerik dan menghasilkan 2 output numerik menggunakan
73
+ arsitektur Cognitive Network yang terinspirasi dari cara kerja otak biologis.
74
+ """,
75
+ examples=[
76
+ ["1.0, 2.0, 3.0, 4.0, 5.0"],
77
+ ["0.5, -1.0, 2.5, 1.5, -0.5"],
78
+ ["0.1, 0.2, 0.3, 0.4, 0.5"]
79
+ ]
80
+ )
81
 
82
  if __name__ == "__main__":
 
83
  demo.launch()