Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
MachineTranslationAid.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\TranslatorInterface\Aid;
5
9
18 public function populateQueries(): void {
19 $definition = $this->dataProvider->getDefinition();
20 $translations = $this->dataProvider->getGoodTranslations();
21 $sourceLanguage = $this->group->getSourceLanguage();
22 $targetLanguage = $this->handle->getCode();
23
24 if ( trim( $definition ) === '' ) {
25 return;
26 }
27
28 foreach ( $this->getWebServices() as $service ) {
29 if ( $service->checkTranslationServiceFailure() ) {
30 continue;
31 }
32
33 try {
34 if ( $service->isSupportedLanguagePair( $sourceLanguage, $targetLanguage ) ) {
35 $this->storeQuery( $service, $sourceLanguage, $targetLanguage, $definition );
36 continue;
37 }
38
39 // Search for translations which we can use as a source for MT
40 // @todo: Support setting priority of languages like Yandex used to have
41 foreach ( $translations as $alternateSourceLanguage => $text ) {
42 if ( !$service->isSupportedLanguagePair( $alternateSourceLanguage, $targetLanguage ) ) {
43 continue;
44 }
45
46 $this->storeQuery( $service, $alternateSourceLanguage, $targetLanguage, $text );
47 break;
48 }
50 throw new TranslationHelperException( $service->getName() . ': ' . $e->getMessage() );
51 }
52 }
53 }
54
55 public function getData(): array {
56 $suggestions = [ '**' => 'suggestion' ];
57
58 foreach ( $this->getQueryData() as $queryData ) {
59 $suggestions[] = $this->formatSuggestion( $queryData );
60 }
61
62 return array_filter( $suggestions );
63 }
64
65 protected function formatSuggestion( array $queryData ): ?array {
66 $service = $queryData['service'];
67 $response = $queryData['response'];
68 $sourceLanguage = $queryData['language'];
69 $sourceText = $queryData['text'];
70
71 $result = $service->getResultData( $response );
72 if ( $result === null ) {
73 return null;
74 }
75
76 return [
77 'target' => $result,
78 'service' => $service->getName(),
79 'source_language' => $sourceLanguage,
80 'source' => $sourceText,
81 ];
82 }
83
85 private function getWebServices(): array {
86 global $wgTranslateTranslationServices;
87
88 $services = [];
89 foreach ( $wgTranslateTranslationServices as $name => $config ) {
90 $service = TranslationWebService::factory( $name, $config );
91 if ( !$service || $service->getType() !== 'mt' ) {
92 continue;
93 }
94
95 $services[$name] = $service;
96 }
97
98 return $services;
99 }
100}
Translation aid that provides suggestion from machine translation services.
storeQuery(TranslationWebService $service, string $from, string $to, string $text)
Stores a web service query for later execution.
Translation helpers can throw this exception when they cannot do anything useful with the current mes...