-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.php
126 lines (110 loc) · 4.38 KB
/
functions.php
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
<?php
// Configuration settings for the CoreNLP service
$corenlp_url = getenv('CORENLP_URL');
$corenlp_user = getenv('CORENLP_USER');
$corenlp_password = getenv('CORENLP_PASSWORD');
/**
* Custom error handler to provide more descriptive error messages.
* Specifically handles unauthorized access and other errors.
*
* @param int $errno Error number
* @param string $errstr Error message
* @param string $errfile File in which the error occurred
* @param int $errline Line number on which the error occurred
*/
function customErrorHandler($errno, $errstr, $errfile, $errline)
{
if (strpos($errstr, '401 Unauthorized') !== false) {
exit('服务授权失败'); // Service authorization failed
}
exit("An error occurred: [$errno] $errstr<br>Error on line $errline in $errfile<br>");
}
set_error_handler("customErrorHandler");
// List of supported languages and their configurations
$languages = ['en', 'es'];
$jsonData = [];
// Load language-specific configurations from JSON files
foreach ($languages as $lang) {
$fileContent = @file_get_contents($lang . '.json');
if ($fileContent === false) {
exit("Error reading $lang.json file.");
}
$jsonData[$lang] = json_decode($fileContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
exit("Error decoding $lang.json: " . json_last_error_msg());
}
}
// Process user input and set default values if not provided
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$userText = $jsonData['en']['defaultSentence'];
} else {
$userText = $_POST['text'] ?? '';
}
// Truncate the user's input without cutting a word in half and append " ..."
if (strlen($userText) > 1000) {
$userText = substr($userText, 0, 1000);
$lastSpacePosition = strrpos($userText, ' ');
if ($lastSpacePosition !== false) {
$userText = substr($userText, 0, $lastSpacePosition);
}
$userText .= " ...";
}
/**
* Colorizes the given text based on its part-of-speech tags.
*
* @param string $text The text to be colorized
* @param string $language The language of the text (e.g., 'en', 'es', 'fr')
* @return string The colorized HTML representation of the text
*/
function colorize($text, $language)
{
global $jsonData, $corenlp_url, $corenlp_user, $corenlp_password;
$colorScheme = $jsonData[$language]['colors'];
$text = $text ?: $jsonData[$language]['defaultSentence'];
// Initialize cURL to communicate with the CoreNLP service
$ch = curl_init();
$getParams = http_build_query([
'properties' => json_encode(['annotators' => 'tokenize,ssplit,pos', 'outputFormat' => 'json']),
'pipelineLanguage' => $language,
]);
curl_setopt($ch, CURLOPT_URL, "$corenlp_url?$getParams");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $text);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Basic ' . base64_encode("$corenlp_user:$corenlp_password"),
'Content-Type: application/x-www-form-urlencoded',
]);
// Execute the cURL request and handle the response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 200 && $httpCode < 300) {
// Successful response
$data = json_decode($response, true);
} else {
// Handle error based on HTTP status code
exit('HTTP error: ' . $httpCode);
}
if (curl_errno($ch)) {
exit('好像出了点问题。待会儿再试试吧。');
}
curl_close($ch);
// Convert the CoreNLP response to colorized HTML
$colorizedHtml = '';
foreach ($data['sentences'] as $index => $sentence) {
$colorizedHtml .= "<p><span class='sentence-id' data-sentence-id='{$index}'>" . ($index + 1) . ".</span> ";
foreach ($sentence['tokens'] as $token) {
$pos = $token['pos'];
$color = $colorScheme[$pos] ?? '#FFFFFF';
$colorizedHtml .= "<span class='word' data-pos='$pos' style='background-color:$color; border-radius: 5px; padding: 2px 5px; margin: 2px;'>{$token['word']}</span> ";
}
$colorizedHtml .= "</p>";
if (strpos(end($sentence['tokens'])['after'], "\n") !== false) {
$colorizedHtml .= "<hr>";
}
}
return $colorizedHtml;
}
$language = $_POST['language'] ?? 'en';
$colorizedHtml = ($_SERVER['REQUEST_METHOD'] === 'POST') ? colorize($userText, $language) : '';
?>