Parse markdown

This commit is contained in:
2025-04-04 01:02:00 +00:00
parent eb8653696e
commit ec03f11b93
3 changed files with 146 additions and 141 deletions

View File

@@ -6,7 +6,8 @@ use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
use DeepL\Translator;
use SteelyWing\Chinese\Chinese;
use DeepL\TranslateTextOptions;
use lucadevelop\TelegramEntitiesDecoder\EntityDecoder;
// This class name is magic
class GenericmessageCommand extends SystemCommand
@@ -39,26 +40,30 @@ class GenericmessageCommand extends SystemCommand
$text_english_count = count(preg_split('~[^a-z 0-9\'\",.]*~i', $text, 0, PREG_SPLIT_NO_EMPTY));
if ($text_english_count >= ($text_chara_count*2 /3)) {
$sourceLang = 'en';
$targetLang = 'zh';
$targetLang = 'zh-hans';
} else {
$sourceLang = 'zh';
$targetLang = 'en-US';
$text = (new Chinese())->to(Chinese::ZH_HANS, $text);
}
$deeplOptions = [
'formality' => 'prefer_less',
'model_type' => 'prefer_quality_optimized',
TranslateTextOptions::FORMALITY => 'prefer_less',
TranslateTextOptions::MODEL_TYPE => 'prefer_quality_optimized',
TranslateTextOptions::TAG_HANDLING => 'html',
];
try {
$glosasaryConfig = json_decode(file_get_contents(__DIR__ . '/../../glossary.json'), true);
if (isset($glosasaryConfig[$sourceLang][$targetLang])) {
$deeplOptions['glossary'] = $glosasaryConfig[$sourceLang][$targetLang];
$targetLangKey = explode('-', $targetLang)[0];
if (isset($glosasaryConfig[$sourceLang][$targetLangKey])) {
$deeplOptions[TranslateTextOptions::GLOSSARY] = $glosasaryConfig[$sourceLang][$targetLangKey];
}
} catch(\Exception $e) {}
$this->translator = new Translator($deepl_api_key);
try {
$translated = $this->translator->translateText($text, $sourceLang, $targetLang, $deeplOptions);
$decoded_text = (new EntityDecoder('HTML'))->decode(json_decode($message->toJson()));
$translated = $this->translator->translateText($decoded_text, $sourceLang, $targetLang, $deeplOptions);
$translated = $translated->text;
} catch (\Exception $e) {
return $this->replyToChat(get_class($e) . ': ' . $e->getMessage()); // ?? var_export($e, true)
}
@@ -68,6 +73,6 @@ class GenericmessageCommand extends SystemCommand
$translated = $message_forwarded_from . ': ' . $translated;
}
return $this->replyToChat($translated, ['disable_notification' => true]);
return $this->replyToChat($translated, ['disable_notification' => true, 'parse_mode' => 'HTML']);
}
}