diff options
| author | ilotterytea <iltsu@alright.party> | 2025-07-04 23:02:47 +0500 |
|---|---|---|
| committer | ilotterytea <iltsu@alright.party> | 2025-07-04 23:02:47 +0500 |
| commit | af1648420b1a343aa95d3cd3abe89c5283c7aaba (patch) | |
| tree | bf7a8ddf07c4e3cd76cda6c17e7c60c431f4e209 | |
| parent | 3e977ece6912634ac63cdf15d34f11f222813691 (diff) | |
feat: an endpoint for asking questions
| -rw-r--r-- | ask.php | 71 |
1 files changed, 71 insertions, 0 deletions
@@ -0,0 +1,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); +?> |
