From af1648420b1a343aa95d3cd3abe89c5283c7aaba Mon Sep 17 00:00:00 2001 From: ilotterytea Date: Fri, 4 Jul 2025 23:02:47 +0500 Subject: feat: an endpoint for asking questions --- ask.php | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 ask.php diff --git a/ask.php b/ask.php new file mode 100644 index 0000000..d334deb --- /dev/null +++ b/ask.php @@ -0,0 +1,71 @@ +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); +?> -- cgit v1.2.3