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
|
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';
$question = $_POST['question'] ?? null;
$max_length = min(max(intval($_POST['max_length'] ?? '100'), 20), 200);
$db = new PDO(DB_URL, DB_USER, DB_PASS);
// choosing a random word from the question
$question_parts = $question ? explode(' ', $question ?? '') : [];
$start_word = null;
while ($start_word == null && !empty($question_parts)) {
$word_index = random_int(0, count($question_parts) - 1);
$start_word = $question_parts[$word_index];
$stmt = $db->prepare('SELECT id FROM chains WHERE from_word = ?');
$stmt->execute([$start_word]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
$start_word = null;
array_splice($question_parts, $word_index, 1);
}
}
// selecting a random word from db if there is no question
if (!$question) {
$stmt = $db->query('SELECT from_word FROM chains ORDER BY rand() LIMIT 1');
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$start_word = $row['from_word'];
}
}
if (!$start_word && !$question) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode([
'status_code' => 400,
'message' => 'No question.',
'data' => null
], JSON_UNESCAPED_SLASHES);
exit;
}
// generating markov chain
$output = [];
while (strlen(implode(' ', $output)) < $max_length) {
array_push($output, $start_word);
$stmt = $db->prepare('SELECT to_word FROM chains WHERE from_word = ? ORDER BY rand() LIMIT 1');
$stmt->execute([$start_word]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
break;
}
$start_word = $row['to_word'];
}
header('Content-Type: application/json');
echo json_encode([
'status_code' => 200,
'message' => null,
'data' => [
'answer' => implode(' ', $output) ?: '...'
]
], JSON_UNESCAPED_SLASHES);
?>
|