-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.php
More file actions
246 lines (198 loc) · 8.41 KB
/
backend.php
File metadata and controls
246 lines (198 loc) · 8.41 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
ini_set('memory_limit', '256M');
require 'vendor/autoload.php';
use Niiknow\Bayes;
header('Content-Type: application/json');
class TransactionSystem {
private $dataFile = 'data.json';
private $data;
private $userId;
private $classifier;
public function __construct() {
$this->loadData();
$this->userId = $this->getUserId();
$this->initializeUser();
// Ensure the models directory exists
if (!is_dir('models')) {
mkdir('models', 0777, true);
}
// Initialize the classifier with a custom tokenizer
$this->classifier = new Bayes(['tokenizer' => $this->getCustomTokenizer()]);
$this->loadClassifier();
}
private function getCustomTokenizer() {
return function ($text) {
// Convert text to lowercase
$text = mb_strtolower($text);
// Use a regex to split text into words and numbers
preg_match_all('/\b\w+\b/', $text, $matches);
// Return the first match (list of words and numbers)
return $matches[0];
};
}
private function getUserId() {
$input = json_decode(file_get_contents('php://input'), true);
return $input['userId'] ?? 'default';
}
private function loadData() {
if (!file_exists($this->dataFile)) {
file_put_contents($this->dataFile, json_encode(['users' => []]));
}
$this->data = json_decode(file_get_contents($this->dataFile), true);
}
private function initializeUser() {
if (!isset($this->data['users'][$this->userId])) {
$this->data['users'][$this->userId] = [
'transactions' => [],
'categories' => []
];
$this->saveData();
}
}
private function getModelFilePath($userId) {
return "models/model_{$userId}.json";
}
private function saveClassifier() {
$modelFilePath = $this->getModelFilePath($this->userId);
$modelDir = dirname($modelFilePath);
// Ensure the models directory exists
if (!is_dir($modelDir)) {
mkdir($modelDir, 0777, true);
}
// Save the classifier state to the file with pretty JSON formatting
$jsonState = $this->classifier->toJson();
$prettyJsonState = json_encode(json_decode($jsonState), JSON_PRETTY_PRINT);
file_put_contents($modelFilePath, $prettyJsonState);
}
private function loadClassifier() {
$modelFilePath = $this->getModelFilePath($this->userId);
if (file_exists($modelFilePath)) {
$jsonState = file_get_contents($modelFilePath);
$this->classifier->fromJson($jsonState);
}
}
public function handleRequest() {
try {
$input = json_decode(file_get_contents('php://input'), true);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Only POST requests are supported');
}
if (!isset($input['action'])) {
throw new Exception('Action parameter is required');
}
$this->handleAction($input);
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
exit;
}
}
private function handleAction($input) {
switch ($input['action']) {
case 'getTransactions':
$this->getTransactions();
break;
case 'predict':
if (empty($input['description'])) {
throw new Exception('Description is required for prediction');
}
$this->predictCategory($input['description']);
break;
case 'train':
if (empty($input['description']) || empty($input['category'])) {
throw new Exception('Description and category are required for training');
}
$this->trainModel($input['description'], $input['category']);
break;
case 'savePrediction':
if (empty($input['description']) || empty($input['category'])) {
throw new Exception('Description and category are required for saving prediction');
}
$this->savePrediction($input['description'], $input['category']);
break;
case 'bulkUpdate':
if (empty($input['updates']) || !is_array($input['updates'])) {
throw new Exception('Updates array is required for bulk update');
}
$this->bulkUpdate($input['updates']);
break;
case 'retrain':
$this->retrainModel();
break;
case 'getProbabilities': // New action for probabilities
if (empty($input['description'])) {
throw new Exception('Description is required for getting probabilities');
}
$this->getProbabilities($input['description']);
break;
default:
throw new Exception('Invalid action specified');
}
}
private function getTransactions() {
$transactions = $this->data['users'][$this->userId]['transactions'];
echo json_encode(['transactions' => $transactions]);
}
private function predictCategory($description) {
$category = $this->classifier->categorize($description);
$this->addTransaction($description, $category);
echo json_encode(['category' => $category]);
}
private function trainModel($description, $category) {
$this->classifier->learn($description, $category);
$this->saveClassifier();
$this->addTransaction($description, $category);
echo json_encode(['status' => 'success']);
}
private function savePrediction($description, $category) {
$this->addTransaction($description, $category);
echo json_encode(['status' => 'success']);
}
private function bulkUpdate($updates) {
foreach ($updates as $update) {
if (!isset($this->data['users'][$this->userId]['transactions'][$update['transactionIndex']])) {
throw new Exception("Invalid transaction index: {$update['transactionIndex']}");
}
$transaction = &$this->data['users'][$this->userId]['transactions'][$update['transactionIndex']];
$transaction['category'] = $update['newCategory'];
if (!in_array($update['newCategory'], $this->data['users'][$this->userId]['categories'])) {
$this->data['users'][$this->userId]['categories'][] = $update['newCategory'];
}
}
$this->saveData();
$this->retrainModel();
echo json_encode(['status' => 'success']);
}
private function retrainModel() {
$transactions = $this->data['users'][$this->userId]['transactions'];
if (empty($transactions)) {
throw new Exception('No transactions available for training');
}
$this->classifier = new Bayes(['tokenizer' => $this->getCustomTokenizer()]);
foreach ($transactions as $transaction) {
$this->classifier->learn($transaction['description'], $transaction['category']);
}
$this->saveClassifier();
}
private function getProbabilities($description) {
// Get the probabilities for the given description
$probabilities = $this->classifier->probabilities($description);
// Return the probabilities as a JSON response
echo json_encode(['probabilities' => $probabilities]);
}
private function addTransaction($description, $category) {
$this->data['users'][$this->userId]['transactions'][] = [
'description' => $description,
'category' => $category
];
if (!in_array($category, $this->data['users'][$this->userId]['categories'])) {
$this->data['users'][$this->userId]['categories'][] = $category;
}
$this->saveData();
}
private function saveData() {
file_put_contents($this->dataFile, json_encode($this->data, JSON_PRETTY_PRINT));
}
}
// Initialize and run the system
(new TransactionSystem())->handleRequest();