跳转到内容

模組:ZhLangconv/sandbox

本页使用了标题或全文手工转换
维基百科,自由的百科全书
--[[
A zhwiki-specific, on-wiki substitute for mw.langconv.

The API is compatible with pending upstream library mw.langconv. See
https://gerrit.wikimedia.org/r/c/mediawiki/core/+/1338066

Conversion is delegated to the <langconvert> parser extension tag. This
module intentionally does not implement parseRule(), since <langconvert>
only exposes dictionary conversion.

Local extension: convert() and convertToVariants() default to sloppy mode,
escaping common ASCII wikitext punctuation in one pass. Pass a third argument,
{ sloppy = false }, to use the full mw.text.nowiki() escaping instead.
Whitespace remains unchanged: paragraphs, leading-space preformatted text and
magic links (if enabled) can still be interpreted, so this mode does not
guarantee a plain-text round trip.
For template calls to convert, use |sloppy=0 to opt out.

AI SLOP WARNING: UNREVIEWED LLM OUTPUT. USE WITH CAUTION!
]]

local langconv = {}
local lc = nil -- ZhConverter for template usage
local util = require 'libraryUtil'
local frame = mw.getCurrentFrame()

-- Temporary manual profiling. os.clock() measures CPU time, not wall time.
-- Totals accumulate for this module instance; dumpProfile() logs them on demand.
local profile = {}
local profileOrder = {}
local function recordTime( name, started, bytes )
	local elapsed = os.clock() - started
	local entry = profile[name]
	if not entry then
		entry = { calls = 0, seconds = 0, bytes = 0 }
		profile[name] = entry
		profileOrder[#profileOrder + 1] = name
	end
	entry.calls = entry.calls + 1
	entry.seconds = entry.seconds + elapsed
	entry.bytes = entry.bytes + ( bytes or 0 )
end

function langconv.resetProfile()
	profile = {}
	profileOrder = {}
end

function langconv.dumpProfile()
	local lines = { 'Langconv CPU profile (inclusive totals; rows may overlap):',
		'stage | calls | total ms | mean ms | input bytes' }
	for _, name in ipairs( profileOrder ) do
		local entry = profile[name]
		lines[#lines + 1] = string.format(
			'%s | %d | %.3f | %.3f | %d', name, entry.calls,
			entry.seconds * 1000, entry.seconds * 1000 / entry.calls, entry.bytes
		)
	end
	local report = table.concat( lines, '\n' )
	mw.log( report )
	return report
end

-- [[phab:T426195]]
--[[
local variants = {
	'zh',
	'zh-hans',
	'zh-hant',
	'zh-cn',
	'zh-hk',
	'zh-mo',
	'zh-my',
	'zh-sg',
	'zh-tw',
}

-- <langconvert> requires canonical BCP 47 codes, not MediaWiki's internal
-- compatibility codes.
local bcp47ByVariant = {
	['zh'] = 'zh',
	['zh-hans'] = 'zh-Hans',
	['zh-hant'] = 'zh-Hant',
	['zh-cn'] = 'zh-Hans-CN',
	['zh-hk'] = 'zh-Hant-HK',
	['zh-mo'] = 'zh-Hant-MO',
	['zh-my'] = 'zh-Hans-MY',
	['zh-sg'] = 'zh-Hans-SG',
	['zh-tw'] = 'zh-Hant-TW',
}
]]

local variants = {
	'zh',
	'zh-hans',
	'zh-hant',
}
local bcp47ByVariant = {
	['zh'] = 'zh',
	['zh-hans'] = 'zh-hans',
	['zh-hant'] = 'zh-hant',
}

local variantAliases = {}
local variantSet = {}
for _, variant in ipairs( variants ) do
	variantSet[variant] = true
	variantAliases[variant] = variant
	variantAliases[string.lower( bcp47ByVariant[variant] )] = variant
end

local fallbacks = {
	['zh'] = { 'zh-hans', 'zh-hant', 'zh-cn', 'zh-tw', 'zh-hk', 'zh-sg', 'zh-mo', 'zh-my' },
	['zh-hans'] = { 'zh-cn', 'zh-sg', 'zh-my' },
	['zh-hant'] = { 'zh-tw', 'zh-hk', 'zh-mo' },
	['zh-cn'] = { 'zh-hans', 'zh-sg', 'zh-my' },
	['zh-hk'] = { 'zh-mo', 'zh-hant', 'zh-tw' },
	['zh-mo'] = { 'zh-hk', 'zh-hant', 'zh-tw' },
	['zh-my'] = { 'zh-sg', 'zh-hans', 'zh-cn' },
	['zh-sg'] = { 'zh-my', 'zh-hans', 'zh-cn' },
	['zh-tw'] = { 'zh-hant', 'zh-hk', 'zh-mo' },
}

local function cloneList( list )
	local copy = {}
	for i, value in ipairs( list ) do
		copy[i] = value
	end
	return copy
end

local function normalizeChineseVariant( variant )
	if type( variant ) ~= 'string' then
		return nil
	end
	return variantAliases[string.lower( variant )]
end


-- Before [[gitiles:mediawiki/core/+/4e6b470be]] (1.46.0-wmf.24), <langconvert>
-- used an opaque general strip marker. It now uses a nowiki strip marker, which
-- can be resolved from Scribunto.
local probeText = 'x'
local probeStarted = os.clock()
local probeResult = frame:extensionTag(
	'langconvert', probeText, { from = 'zh', to = 'zh' }
)
local canUnstripLangconvert = mw.text.unstripNoWiki( probeResult ) == probeText
recordTime( 'initialization probe', probeStarted, #probeText )

local sloppyEscapes = {
	['&'] = '&#38;', ["'"] = '&#39;',
	['{'] = '&#123;', ['}'] = '&#125;',
	['<'] = '&#60;', ['>'] = '&#62;',
	['['] = '&#91;', [']'] = '&#93;',
	['='] = '&#61;',
	['*'] = '&#42;', ['#'] = '&#35;', [';'] = '&#59;', [':'] = '&#58;',
	['_'] = '&#95;', ['-'] = '&#45;',
}

local function escapeText( text, sloppy )
	if not canUnstripLangconvert then
		error( 'MediaWiki 1.46.0-wmf.24 or later is required', 2 )
	end
	local started = os.clock()
	local escaped
	if sloppy then
		-- One pass also protects entities, formatting, list/heading markers,
		-- URL schemes and behavior switches. Replacements are not re-escaped.
		-- Leave whitespace alone to avoid an entity for every space/newline.
		-- Double quotes, pipes, exclamation marks and plus signs stay literal;
		-- tag/table delimiters are already escaped. Signature expansion on
		-- save is outside this parsing step, so tildes are left literal too.
		escaped = string.gsub( text, '[&\'{}<>%[%]=*#;:_%-]', sloppyEscapes )
	else
		escaped = mw.text.nowiki( text )
	end
	recordTime( sloppy and 'escape sloppy' or 'nowiki', started, #text )
	return escaped
end

local function convertEscapedText( escaped, variant )
	local started = os.clock()
	local result = frame:extensionTag(
		'langconvert', escaped,
		{ from = 'zh', to = bcp47ByVariant[variant] }
	)
	-- Includes the Lua/PHP boundary as well as the PHP parser and converter.
	recordTime( 'extensionTag ' .. variant, started, #escaped )
	started = os.clock()
	result = mw.text.unstripNoWiki( result )
	recordTime( 'unstripNoWiki', started )
	started = os.clock()
	local decoded = mw.text.decode( result, false )
	recordTime( 'decode', started, #result )
	return decoded
end

local function convertText( text, variant, sloppy )
	local totalStarted = os.clock()
	local decoded = convertEscapedText( escapeText( text, sloppy ), variant )
	recordTime( 'convertText total', totalStarted, #text )
	return decoded
end

local function getSloppyOption( methodName, options )
	local name = 'mw.langconv:' .. methodName
	util.checkType( name, 3, options, 'table', true )
	if options then
		util.checkTypeForNamedArg( name, 'sloppy', options.sloppy, 'boolean', true )
		return options.sloppy ~= false
	end
	return true
end

local function getTitle( methodName, value )
	util.checkTypeMulti( 'mw.langconv:' .. methodName, 1, value, { 'string', 'table' } )
	if type( value ) == 'string' then
		return mw.title.new( value )
	end
	if type( value.namespace ) ~= 'number' or
		type( value.text ) ~= 'string' or
		type( value.prefixedText ) ~= 'string' then
		error(
			"bad argument #1 to 'mw.langconv:" .. methodName ..
				"' (mw.title object expected)",
			3
		)
	end
	return value
end

local function splitPlain( text, separator )
	local parts = {}
	local start = 1
	while true do
		local position = string.find( text, separator, start, true )
		if not position then
			parts[#parts + 1] = string.sub( text, start )
			return parts
		end
		parts[#parts + 1] = string.sub( text, start, position - 1 )
		start = position + #separator
	end
end

function langconv.isConversionEnabled()
	-- zhwiki enables Chinese conversion, and <langconvert> invokes
	-- LanguageConverter::autoConvert() directly.
	return true
end

function langconv.getConverterLanguageCode( languageCode )
	util.checkType( 'mw.langconv.getConverterLanguageCode', 1, languageCode, 'string' )
	return normalizeChineseVariant( languageCode ) and 'zh' or nil
end

function langconv.new( languageCode )
	util.checkType( 'mw.langconv.new', 1, languageCode, 'string' )
	local canonicalLanguageCode = normalizeChineseVariant( languageCode )
	if not canonicalLanguageCode then
		error( "language code '" .. languageCode .. "' is not supported by this zhwiki module", 2 )
	end

	-- Match core's exact-language construction: only zh gets ZhConverter;
	-- requesting a variant such as zh-tw gets a trivial converter.
	local hasVariants = canonicalLanguageCode == 'zh'
	local converterVariants = hasVariants and variants or { canonicalLanguageCode }
	local converter = {}
	local checkSelf = util.makeCheckSelfFunction(
		'mw.langconv', 'converter', converter, 'language converter object'
	)

	local function requireVariant( methodName, variant, argumentIndex )
		util.checkType( 'mw.langconv:' .. methodName, argumentIndex, variant, 'string' )
		local normalized
		if hasVariants then
			normalized = normalizeChineseVariant( variant )
		elseif string.lower( variant ) == canonicalLanguageCode then
			normalized = canonicalLanguageCode
		end
		if not normalized then
			error(
				"variant code '" .. variant .. "' is invalid for language '" ..
					canonicalLanguageCode .. "'",
				3
			)
		end
		return normalized
	end

	function converter:getLanguageCode()
		checkSelf( self, 'getLanguageCode' )
		return canonicalLanguageCode
	end

	function converter:getVariants()
		checkSelf( self, 'getVariants' )
		return cloneList( converterVariants )
	end

	function converter:hasVariants()
		checkSelf( self, 'hasVariants' )
		return hasVariants
	end

	function converter:getDefaultVariant()
		checkSelf( self, 'getDefaultVariant' )
		return canonicalLanguageCode
	end

	function converter:hasVariant( variant )
		checkSelf( self, 'hasVariant' )
		util.checkType( 'mw.langconv:hasVariant', 1, variant, 'string' )
		if hasVariants then
			return variantSet[variant] == true
		end
		return variant == canonicalLanguageCode
	end

	function converter:normalizeVariant( variant )
		checkSelf( self, 'normalizeVariant' )
		util.checkType( 'mw.langconv:normalizeVariant', 1, variant, 'string' )
		if hasVariants then
			return normalizeChineseVariant( variant )
		end
		return string.lower( variant ) == canonicalLanguageCode and
			canonicalLanguageCode or nil
	end

	function converter:getFallbackVariants( variant )
		checkSelf( self, 'getFallbackVariants' )
		variant = requireVariant( 'getFallbackVariants', variant, 1 )
		return hasVariants and cloneList( fallbacks[variant] ) or { canonicalLanguageCode }
	end

	function converter:convert( text, variant, options )
		checkSelf( self, 'convert' )
		if variant == nil then
			error( 'too few arguments to mw.langconv:convert', 2 )
		end
		util.checkType( 'mw.langconv:convert', 1, text, 'string' )
		variant = requireVariant( 'convert', variant, 2 )
		local sloppy = getSloppyOption( 'convert', options )
		return hasVariants and convertText( text, variant, sloppy ) or text
	end

	function converter:convertToVariants( text, targetVariants, options )
		checkSelf( self, 'convertToVariants' )
		if targetVariants == nil then
			error( 'too few arguments to mw.langconv:convertToVariants', 2 )
		end
		util.checkType( 'mw.langconv:convertToVariants', 1, text, 'string' )
		util.checkTypeMulti(
			'mw.langconv:convertToVariants', 2, targetVariants, { 'string', 'table' }
		)
		local sloppy = getSloppyOption( 'convertToVariants', options )

		local requestedVariants
		if type( targetVariants ) == 'string' then
			if targetVariants ~= 'all' then
				error(
					"bad argument #2 to 'mw.langconv:convertToVariants' " ..
						"(literal 'all' or table expected, got string)",
					2
				)
			end
			requestedVariants = converterVariants
		else
			requestedVariants = targetVariants
		end

		local totalStarted = os.clock()
		local converted = {}
		local escaped
		for _, variant in pairs( requestedVariants ) do
			local normalized = requireVariant( 'convertToVariants', variant, 2 )
			if converted[normalized] == nil then
				if hasVariants then
					-- Escape once, and only if at least one conversion is requested.
					if escaped == nil then
						escaped = escapeText( text, sloppy )
					end
					converted[normalized] = convertEscapedText( escaped, normalized )
				else
					converted[normalized] = text
				end
			end
		end
		recordTime( 'convertToVariants total', totalStarted, #text )
		return converted
	end

	function converter:getNamespaceName( namespaceId, variant )
		checkSelf( self, 'getNamespaceName' )
		util.checkType( 'mw.langconv:getNamespaceName', 1, namespaceId, 'number' )
		variant = requireVariant( 'getNamespaceName', variant, 2 )
		local namespace = mw.site.namespaces[namespaceId]
		if not namespace then
			error( "namespace ID '" .. namespaceId .. "' is invalid", 2 )
		end
		return hasVariants and convertText( namespace.name, variant ) or namespace.name
	end

	function converter:convertTitle( title, variant )
		checkSelf( self, 'convertTitle' )
		if variant == nil then
			error( 'too few arguments to mw.langconv:convertTitle', 2 )
		end
		local titleObject = getTitle( 'convertTitle', title )
		variant = requireVariant( 'convertTitle', variant, 2 )
		if not titleObject then
			return nil
		end
		if not hasVariants then
			return titleObject.prefixedText
		end
		local namespace = self:getNamespaceName( titleObject.namespace, variant )
		local text = convertText( titleObject.text, variant )
		return namespace == '' and text or namespace .. ':' .. text
	end

	-- Resolve each item to the exact title or the first existing variant.
	-- Cloned from core's LinkHolderArray::doVariants().
	function converter:resolveVariantBatch( titles, options )
		checkSelf( self, 'resolveVariantBatch' )
		if titles == nil then
			error( 'too few arguments to mw.langconv:resolveVariantBatch', 2 )
		end
		util.checkType( 'mw.langconv:resolveVariantBatch', 1, titles, 'table' )
		util.checkType( 'mw.langconv:resolveVariantBatch', 2, options, 'table', true )
		options = options or {}
		util.checkTypeForNamedArg(
			'mw.langconv:resolveVariantBatch', 'preferNonRedirect',
			options.preferNonRedirect, 'boolean', true
		)
		local preferNonRedirect = options.preferNonRedirect or false

		local titleCount = 0
		for _ in pairs( titles ) do
			titleCount = titleCount + 1
		end

		local titleSpecs = {}
		local resolvableIndexes = {}
		for i = 1, titleCount do
			local title = titles[i]
			if title == nil then
				error(
					"bad argument #1 to 'mw.langconv:resolveVariantBatch' " ..
						'(contiguous list expected)',
					2
				)
			end
			if type( title ) ~= 'table' or
				type( title.namespace ) ~= 'number' or
				type( title.text ) ~= 'string' or
				type( title.isLocal ) ~= 'boolean' then
				error(
					"bad argument #1 to 'mw.langconv:resolveVariantBatch' " ..
						'(mw.title object expected at index ' .. i .. ')',
					2
				)
			end
			if title.isLocal and title.namespace >= 0 and title.text ~= '' then
				resolvableIndexes[#resolvableIndexes + 1] = i
				titleSpecs[#titleSpecs + 1] = {
					namespace = title.namespace,
					text = title.text,
				}
			end
		end

		local resolved = {}
		if #titleSpecs == 0 then
			return resolved
		end

		local candidateTexts = {}
		local candidateIndexesByText = {}
		local candidatesByTitle = {}
		local candidateIndexSets = {}
		for position = 1, #titleSpecs do
			candidatesByTitle[position] = {}
			candidateIndexSets[position] = {}
		end

		local function addCandidate( position, namespace, text )
			local title = mw.title.makeTitle( namespace, text )
			local key = title.prefixedText
			local candidateIndex = candidateIndexesByText[key]
			if not candidateIndex then
				candidateIndex = #candidateTexts + 1
				candidateIndexesByText[key] = candidateIndex
				candidateTexts[candidateIndex] = key
			end
			local indexes = candidatesByTitle[position]
			if not candidateIndexSets[position][candidateIndex] then
				candidateIndexSets[position][candidateIndex] = true
				indexes[#indexes + 1] = candidateIndex
			end
		end

		local sourceTexts = {}
		for position, spec in ipairs( titleSpecs ) do
			sourceTexts[position] = spec.text
			addCandidate( position, spec.namespace, spec.text )
		end

		if hasVariants then
			-- ASCII control characters cannot occur in valid titles. NUL and \4
			-- are unsuitable because LanguageConverter::autoConvert() removes them.
			local separator = '\1'
			local joined = table.concat( sourceTexts, separator )
			for _, variant in ipairs( variants ) do
				local convertedTexts = splitPlain( convertText( joined, variant ), separator )
				if #convertedTexts ~= #titleSpecs then
					error( 'Language converter did not preserve title separators', 2 )
				end
				for position, spec in ipairs( titleSpecs ) do
					addCandidate( position, spec.namespace, convertedTexts[position] )
				end
			end
		end

		local candidates = mw.title.newBatch( candidateTexts )
			:lookupExistence()
			:getTitles()
		for position, inputIndex in ipairs( resolvableIndexes ) do
			local firstRedirect
			for _, candidateIndex in ipairs( candidatesByTitle[position] ) do
				local candidate = candidates[candidateIndex]
				if candidate and candidate.exists then
					if not preferNonRedirect or not candidate.isRedirect then
						resolved[inputIndex] = candidate
						break
					end
					firstRedirect = firstRedirect or candidate
				end
			end
			resolved[inputIndex] = resolved[inputIndex] or firstRedirect
		end
		return resolved
	end

	function converter:resolveVariantTitle( title )
		checkSelf( self, 'resolveVariantTitle' )
		if title == nil then
			error( 'too few arguments to mw.langconv:resolveVariantTitle', 2 )
		end
		local titleObject = getTitle( 'resolveVariantTitle', title )
		if not titleObject then
			return nil
		end
		return self:resolveVariantBatch( { titleObject } )[1]
	end

	function converter:markNoConversion( text )
		checkSelf( self, 'markNoConversion' )
		util.checkType( 'mw.langconv:markNoConversion', 1, text, 'string' )
		if not hasVariants or string.find( text, '-{', 1, true ) or
			string.find( text, '}-', 1, true ) then
			return text
		end
		return '-{R|' .. text .. '}-'
	end

	return converter
end

-- For template calls via #invoke

-- Add |profile=1 to dump cumulative timings to Scribunto's log after the call.
local function finish( frame, result )
	local p = ''
	if frame.args.profile == '1' then
		p = langconv.dumpProfile()
	end
	return result .. '\n<pre>' .. p .. '</pre>'
end

local function getArgument( args, name, index )
	local value = args[name]
	if value == nil then
		value = args[index]
	end
	return value
end

function langconv.convert( frame )
	local text = getArgument( frame.args, 'text', 1 ) or ''
	local variant = getArgument( frame.args, 'variant', 2 )

	if not variant or mw.text.trim( variant ) == '' then
		error( 'variant must be specified', 2 )
	end

	if not lc then
		lc = langconv.new( 'zh' )
	end
	return finish( frame, lc:convert(
		text, mw.text.trim( variant ), { sloppy = frame.args.sloppy ~= '0' }
	) )
end

function langconv.resolve( frame )
	local title = getArgument( frame.args, 'title', 1 )
	if not title or mw.text.trim( title ) == '' then
		return finish( frame, '' )
	end
	local options = nil
	if frame.args['preferNonRedirect'] then
		local yesno = require( 'Module:Yesno' )
		options = {['preferNonRedirect'] = yesno(frame.args['preferNonRedirect'])}
	end


	if not lc then
		lc = langconv.new( 'zh' )
	end
	local resolved = lc:resolveVariantBatch(
		{ mw.title.new( title ) },
		options
	)[1]
	return finish( frame, resolved and resolved.prefixedText or '' )
end


return langconv