Debian Codegraph @

maintenance/compareLanguageConverterOutput.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Maintenance
20 */
21
22 use MediaWiki\Config\ServiceOptions;
23 use MediaWiki\Content\TextContent;
24 use MediaWiki\Language\Language;
25 use MediaWiki\Parser\ParserOptions;
26 use MediaWiki\Parser\ParserOutput;
27 use MediaWiki\Rest\Handler\Helper\PageRestHelperFactory;
28 use MediaWiki\Revision\SlotRecord;
29 use MediaWiki\Title\Title;
30 use MediaWiki\User\User;
31 use Wikimedia\Bcp47Code\Bcp47Code;
32 use Wikimedia\Diff\ArrayDiffFormatter;
33 use Wikimedia\Diff\ComplexityException;
34 use Wikimedia\Diff\Diff;
35 use Wikimedia\Stats\NullStatsdDataFactory;
36 use Wikimedia\Stats\StatsFactory;
37
38 // @codeCoverageIgnoreStart
39 require_once __DIR__ . '/Maintenance.php';
40 // @codeCoverageIgnoreEnd
41
42 /**
43 * Maintenance script that compares variant conversion output between Parser and
44 * HtmlOutputRendererHelper.
45 *
46 * @ingroup Maintenance
47 */
48 class CompareLanguageConverterOutput extends Maintenance {
49 public function __construct() {
50 parent::__construct();
51 $this->addDescription( 'Compares variant conversion output between Parser and HtmlOutputRendererHelper' );
52 $this->addArg(
53 'page-title',
54 'Name of the page to be parsed and compared',
55 true
56 );
57 $this->addArg(
58 'target-variant',
59 'Target variant language code to transform the content to',
60 true
61 );
62 }
63
64 public function execute() {
65 $mwInstance = $this->getServiceContainer();
66
67 $pageName = $this->getArg( 'page-title' );
68 $pageTitle = Title::newFromText( $pageName );
69
70 if ( !$pageTitle || !$pageTitle->exists() ) {
71 $this->fatalError( "Title with name $pageName not found" );
72 }
73
74 $targetVariantCode = $this->getArg( 'target-variant' );
75 $languageNameUtils = $mwInstance->getLanguageNameUtils();
76 if ( !$languageNameUtils->isValidBuiltInCode( $targetVariantCode ) ) {
77 $this->fatalError( "$targetVariantCode is not a supported variant" );
78 }
79 $targetVariant = $mwInstance->getLanguageFactory()->getLanguage(
80 $targetVariantCode
81 );
82
83 $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
84 $baseLanguage = $pageTitle->getPageLanguage();
85
86 $parserOutput = $this->getParserOutput( $pageTitle, $baseLanguage, $targetVariant );
87 $parsoidOutput = $this->getParsoidOutput( $pageTitle, $targetVariant, $user );
88 $converterUsed = $this->getConverterUsed( $parsoidOutput );
89
90 $this->compareOutput( $parserOutput->getContentHolderText(),
91 $parsoidOutput->getText( [ 'deduplicateStyles' => false ] ), $converterUsed );
92 return true;
93 }
94
95 private function newPageRestHelperFactory(): PageRestHelperFactory {
96 $services = $this->getServiceContainer();
97
98 $factory = new PageRestHelperFactory(
99 new ServiceOptions( PageRestHelperFactory::CONSTRUCTOR_OPTIONS, $services->getMainConfig() ),
100 $services->getRevisionLookup(),
101 $services->getRevisionRenderer(),
102 $services->getTitleFormatter(),
103 $services->getPageStore(),
104 $services->getParsoidOutputStash(),
105 new NullStatsdDataFactory(),
106 $services->getParserOutputAccess(),
107 $services->getParsoidSiteConfig(),
108 $services->getHtmlTransformFactory(),
109 $services->getContentHandlerFactory(),
110 $services->getLanguageFactory(),
111 $services->getRedirectStore(),
112 $services->getLanguageConverterFactory(),
113 $services->getTitleFactory(),
114 $services->getConnectionProvider(),
115 $services->getChangeTagsStore(),
116 StatsFactory::newNull()
117 );
118 return $factory;
119 }
120
121 private function getParserOptions( Language $language ): ParserOptions {
122 $parserOpts = ParserOptions::newFromAnon();
123 $parserOpts->setTargetLanguage( $language );
124 $parserOpts->disableContentConversion( false );
125 $parserOpts->disableTitleConversion( false );
126
127 return $parserOpts;
128 }
129
130 private function getParserOutput(
131 Title $pageTitle,
132 Language $baseLanguage,
133 Language $targetVariant
134 ): ParserOutput {
135 // We update the default language variant because we want Parser to
136 // perform variant conversion to it.
137 global $wgDefaultLanguageVariant;
138 $wgDefaultLanguageVariant = $targetVariant->getCode();
139
140 $mwInstance = $this->getServiceContainer();
141
142 $languageFactory = $mwInstance->getLanguageFactory();
143 $parser = $mwInstance->getParser();
144 $parserOptions = $this->getParserOptions(
145 $languageFactory->getParentLanguage( $baseLanguage )
146 );
147
148 $content = $mwInstance->getRevisionLookup()
149 ->getRevisionByTitle( $pageTitle )
150 ->getContent( SlotRecord::MAIN );
151 $wikiContent = ( $content instanceof TextContent ) ? $content->getText() : '';
152
153 $po = $parser->parse( $wikiContent, $pageTitle, $parserOptions );
154 // TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
155 $pipeline = $mwInstance->getDefaultOutputPipeline();
156 $options = [ 'deduplicateStyles' => false ];
157 return $pipeline->run( $po, $parserOptions, $options );
158 }
159
160 private function getParsoidOutput(
161 Title $pageTitle,
162 Bcp47Code $targetVariant,
163 User $user
164 ): ParserOutput {
165 $htmlOutputRendererHelper = $this->newPageRestHelperFactory()->newHtmlOutputRendererHelper( $pageTitle, [
166 'stash' => false,
167 'flavor' => 'view',
168 ], $user );
169 $htmlOutputRendererHelper->setVariantConversionLanguage( $targetVariant );
170
171 return $htmlOutputRendererHelper->getHtml();
172 }
173
174 private function getWords( string $output ): array {
175 $tagsRemoved = strip_tags( $output );
176 $words = preg_split( '/\s+/', trim( $tagsRemoved ), -1, PREG_SPLIT_NO_EMPTY );
177 return $words;
178 }
179
180 private function getBody( string $output ): string {
181 $dom = new DOMDocument();
182 // phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
183 @$dom->loadHTML( $output );
184 $body = $dom->getElementsByTagName( 'body' )->item( 0 );
185 if ( $body === null ) {
186 // Body element not present
187 return $output;
188 }
189
190 return $body->textContent;
191 }
192
193 private function compareOutput(
194 string $parserText,
195 string $parsoidText,
196 string $converterUsed
197 ): void {
198 $parsoidWords = $this->getWords( $this->getBody( $parsoidText ) );
199 $parserWords = $this->getWords( $parserText );
200
201 $parserWordCount = count( $parserWords );
202 $parsoidWordCount = count( $parsoidWords );
203 $this->output( "Word count: Parsoid: $parsoidWordCount; Parser: $parserWordCount\n" );
204
205 $this->outputSimilarity( $parsoidWords, $parserWords );
206 $this->output( "\n" );
207 $this->outputDiff( $parsoidWords, $parserWords, $converterUsed );
208 }
209
210 private function getConverterUsed( ParserOutput $parsoidOutput ): string {
211 $isCoreConverterUsed = strpos(
212 $parsoidOutput->getRawText(),
213 'Variant conversion performed using the core LanguageConverter'
214 );
215
216 if ( $isCoreConverterUsed ) {
217 return 'Core LanguageConverter';
218 } else {
219 return 'Parsoid LanguageConverter';
220 }
221 }
222
223 // Inspired from: https://stackoverflow.com/a/55927237/903324
224 private function mb_sprintf( string $format, ...$args ): string {
225 $params = $args;
226
227 return sprintf(
228 preg_replace_callback(
229 '/(?<=%|%-)\d+(?=s)/',
230 static function ( array $matches ) use ( &$params ) {
231 $value = array_shift( $params );
232
233 return (string)( strlen( $value ) - mb_strlen( $value ) + $matches[0] );
234 },
235 $format
236 ),
237 ...$args
238 );
239 }
240
241 private function outputSimilarity( array $parsoidWords, array $parserWords ): void {
242 $parsoidOutput = implode( ' ', $parsoidWords );
243 $parserOutput = implode( ' ', $parserWords );
244 $this->output(
245 'Total characters: Parsoid: ' . strlen( $parsoidOutput ) .
246 '; Parser: ' . strlen( $parserOutput ) . "\n"
247 );
248
249 $similarityPercent = 0;
250 $similarCharacters = similar_text( $parsoidOutput, $parserOutput, $similarityPercent );
251 $similarityPercent = round( $similarityPercent, 2 );
252
253 $this->output(
254 "Similarity via similar_text(): $similarityPercent%; Similar characters: $similarCharacters"
255 );
256 }
257
258 private function outputDiff( array $parsoidWords, array $parserWords, string $converterUsed ): void {
259 $out = str_repeat( '-', 96 ) . "\n";
260 $out .= sprintf( "| %5s | %-35s | %-35s | %-8s |\n", 'Line', 'Parsoid', 'Parser', 'Diff' );
261 $out .= sprintf( "| %5s | %-35s | %-35s | %-8s |\n", '', "($converterUsed)", '', '' );
262 $out .= str_repeat( '-', 96 ) . "\n";
263
264 try {
265 $diff = new Diff( $parsoidWords, $parserWords );
266 } catch ( ComplexityException $e ) {
267 $this->output( $e->getMessage() );
268 $this->error( 'Encountered ComplexityException while computing diff' );
269 }
270
271 // Print the difference between the words
272 $wordDiffFormat = ( new ArrayDiffFormatter() )->format( $diff );
273 foreach ( $wordDiffFormat as $index => $wordDiff ) {
274 $action = $wordDiff['action'];
275 $old = $wordDiff['old'] ?? null;
276 $new = $wordDiff['new'] ?? null;
277
278 $out .= $this->mb_sprintf(
279 "| %5s | %-35s | %-35s | %-8s |\n",
280 str_pad( (string)( $index + 1 ), 5, ' ', STR_PAD_LEFT ),
281 mb_strimwidth( $old ?? '- N/A -', 0, 35, '…' ),
282 mb_strimwidth( $new ?? '- N/A -', 0, 35, '…' ),
283 $action
284 );
285 }
286
287 // Print the footer.
288 $out .= str_repeat( '-', 96 ) . "\n";
289 $this->output( "\n" . $out );
290 }
291 }
292
293 // @codeCoverageIgnoreStart
294 $maintClass = CompareLanguageConverterOutput::class;
295 require_once RUN_MAINTENANCE_IF_MAIN;
296 // @codeCoverageIgnoreEnd