跳转到内容

模組:Conversion rule extractor

本页使用了标题或全文手工转换
维基百科,自由的百科全书

这是本页的一个历史版本,由PexEric留言 | 贡献2025年5月3日 (六) 16:00编辑。这可能和当前版本存在着巨大的差异。

local p = {}
local TPV = require('Module:Template parameter value')
local Arguments = require('Module:Arguments') -- 用于模板入口点
local mw_text = require('mw.text') -- 用于分割和裁剪

-- 以下模板的重定向检索于2025-05-03
local NOTE_TA_TEMPLATES = {
    'NoteTA', 'TA', 'NoteAT', 'NoteTA/default', 'NOTETA', 'Note TA', 'Noteta', 'NoteTa', 'NoteTA/lua', '全文字词转换',
    'NoteTA-lite', 'TA-lite', 'TAL', 'TAl'
}

local MAX_LOCAL_RULES = 30
local MAX_GROUP_RULES = 30

--[[--------------------------< 辅助函数 - CGroup 处理 >--------------------------]]
local function loadCGroupData(groupName)
    local moduleTitleStr = 'Module:CGroup/' .. groupName
    local success, data
    local titleObj = mw.title.new(moduleTitleStr)
    if titleObj and titleObj.exists then
        success, data = pcall(mw.loadData, moduleTitleStr)
        if success and type(data) == 'table' then
            return data
        else
            mw.log('ConversionRuleExtractor: Failed to load or parse CGroup module: ' .. moduleTitleStr .. (success and ' (invalid data type)' or ' (load error)'))
            return nil
        end
    end
    return nil
end

local function extractRulesFromCGroupData(data)
    local rules = {}
    if data and data.content and type(data.content) == 'table' then
        for _, item in ipairs(data.content) do
            if type(item) == 'table' and item.type == 'item' and type(item.rule) == 'string' and item.rule ~= '' then
                table.insert(rules, item.rule)
            end
        end
    end
    return rules
end

--[[--------------------------< 辅助函数 - 规则解析与过滤 >--------------------------]]
local function extractSourceTerms(ruleString)
    local sources = {}
    local rulePart = ruleString
    local arrowPos = string.find(rulePart, '=>', 1, true)
    if arrowPos then
        rulePart = mw_text.trim(string.sub(rulePart, 1, arrowPos - 1))
    end
    for segment in mw_text.gsplit(rulePart, ';') do
        segment = mw_text.trim(segment)
        if segment ~= '' then
            local term
            local colonPos = string.find(segment, ':', 1, true)
            if colonPos then
                term = mw_text.trim(string.sub(segment, colonPos + 1))
            else
                term = segment
            end
            if term ~= '' then
                term = mw_text.strip(term) -- 去除HTML标记
                if term ~= '' then
                    table.insert(sources, term)
                end
            end
        end
    end
    return sources
end

local function filterGroupRulesByText(groupRules, textToMatch)
    if not textToMatch or textToMatch == '' or not groupRules or #groupRules == 0 then
        return {}
    end
    local filteredRules = {}
    local cleanTextToMatch = mw_text.strip(textToMatch)
    if cleanTextToMatch == '' then return {} end

    for _, ruleString in ipairs(groupRules) do
        local sourceTerms = extractSourceTerms(ruleString)
        local matched = false
        for _, term in ipairs(sourceTerms) do
            if string.find(cleanTextToMatch, term, 1, true) then
                matched = true
                break
            end
        end
        if matched then
            table.insert(filteredRules, ruleString)
        end
    end
    return filteredRules
end

--[[--------------------------< 辅助函数 - 格式化输出 >--------------------------]]
local function formatRules(rules, flag)
    if not rules or #rules == 0 then
        return ''
    end
    -- 如果 flag 是 nil 或空字符串,则默认为 'H'
    flag = (type(flag) == 'string' and flag ~= '') and flag or 'H'

    if flag == 'raw' then
        -- 对 raw 标志,使用换行符连接
        return table.concat(rules, "\n")
    else
        -- 对其他标志 (H, A, 等),使用 -{[flag]|...}- 包装并直接连接
        local wrapped_rules = {}
        for _, rule in ipairs(rules) do
            table.insert(wrapped_rules, "-{" .. flag .. "|" .. rule .. "}-")
        end
        return table.concat(wrapped_rules, "") -- 直接连接,无分隔符
    end
end

--[[--------------------------< 核心获取函数 >--------------------------]]
function p._internal_fetchAllRules(pageTitleString)
    local allRules = {
        title = nil,
        ['local'] = {},
        groups = {}
    }
    local foundTemplate = false
    local titleObjCheck = mw.title.new(pageTitleString)
    if not titleObjCheck then
         mw.log('ConversionRuleExtractor: Potentially invalid page title provided for fetching rules: ' .. pageTitleString)
    end

    -- 1. 获取标题规则 (T)
    local success_t, titleRule = TPV.getParameter(pageTitleString, NOTE_TA_TEMPLATES, 'T')
    if success_t then -- 只要 TPV.getParameter 成功执行,即使返回空字符串也记录
        if titleRule and titleRule ~= '' then
             allRules.title = titleRule
             foundTemplate = true
        end
    else
         mw.log('ConversionRuleExtractor: TPV.getParameter failed for T on page ' .. pageTitleString .. ': ' .. tostring(titleRule)) -- 记录获取 T 失败
    end

    -- 2. 获取本地规则 (1..MAX_LOCAL_RULES)
    for i = 1, MAX_LOCAL_RULES do
        local paramName = tostring(i)
        local success_l, localRule = TPV.getParameter(pageTitleString, NOTE_TA_TEMPLATES, paramName)
        if success_l then
            if localRule and localRule ~= '' then
                table.insert(allRules['local'], localRule)
                foundTemplate = true
            end
        else
            if localRule == "No valid template found" and not foundTemplate then
                 if i == 1 then return nil end -- 第一次查询就失败且无T,则无模板
             end
             break -- 优化
        end
    end

    -- 3. 获取组规则 (G1..MAX_GROUP_RULES)
    for i = 1, MAX_GROUP_RULES do
        local paramName = 'G' .. i
        local success_g, groupName = TPV.getParameter(pageTitleString, NOTE_TA_TEMPLATES, paramName)
        if success_g then
            if groupName and groupName ~= '' then
                foundTemplate = true
                local groupData = loadCGroupData(groupName)
                if groupData then
                     local rulesFromGroup = extractRulesFromCGroupData(groupData)
                     if #rulesFromGroup > 0 then
                         table.insert(allRules.groups, { name = groupName, rules = rulesFromGroup })
                     end
                end
            end
        else
             if groupName == "No valid template found" and not foundTemplate then
                 if i == 1 then return nil end -- 第一次查询就失败且无T和local,则无模板
             end
             break -- 优化
        end
    end

    if foundTemplate then
        return allRules
    else
        -- 如果 TPV.getParameter 总是失败(即使模板存在但参数为空),这里可能错误地返回 nil
        -- 但 TPV 应该在找到模板但参数为空时返回 true 和 ""
        -- 因此,如果 foundTemplate 仍为 false,很可能确实没有找到模板或参数
        return nil
    end
end

--[[--------------------------< 公开函数 >--------------------------]]
function p.getFullTextRules(pageTitle, flag)
    local pageTitleString
    if type(pageTitle) == 'string' then
        pageTitleString = pageTitle
    elseif type(pageTitle) == 'userdata' and getmetatable(pageTitle) == 'mw.title' then
         pageTitleString = pageTitle.fullText
    else
        return '<span class="error">错误:无效的页面标题类型。</span>' -- 返回错误信息
    end

    local allRulesData = p._internal_fetchAllRules(pageTitleString)
    if not allRulesData then
        return '' -- 未找到规则则返回空
    end

    local combinedRules = {}
    if allRulesData['local'] then
        for _, rule in ipairs(allRulesData['local']) do table.insert(combinedRules, rule) end
    end
    if allRulesData.groups then
        for _, groupInfo in ipairs(allRulesData.groups) do
            if groupInfo.rules then
                for _, rule in ipairs(groupInfo.rules) do table.insert(combinedRules, rule) end
            end
        end
    end

    return formatRules(combinedRules, flag)
end

function p.getTitleRules(pageTitle, flag, outputType, frame)
    local pageTitleString
    local titleObj

    if type(pageTitle) == 'string' then
        pageTitleString = pageTitle
        local success_create, result_or_err = pcall(mw.title.new, pageTitleString)
        if not success_create or type(result_or_err) ~= 'userdata' then
            mw.log('ConversionRuleExtractor: Failed to create title object or invalid type returned for string: "' .. pageTitleString .. '". Error/Result: ' .. tostring(result_or_err))
            return '<span class="error">错误:无法创建标题对象。</span>' -- 返回错误信息
        else
            titleObj = result_or_err
        end
    elseif type(pageTitle) == 'userdata' and getmetatable(pageTitle) == 'mw.title' then
         titleObj = pageTitle
         pageTitleString = titleObj.fullText
    else
        return '<span class="error">错误:无效的页面标题输入类型。</span>' -- 返回错误信息
    end

    if not titleObj or type(titleObj.getText) ~= 'function' then
         mw.log('ConversionRuleExtractor: CRITICAL: titleObj is invalid or missing getText right before use. Page: ' .. (pageTitleString or 'N/A'))
         return '<span class="error">内部错误:无法获取标题文本。</span>' -- 返回错误信息
    end

    local titleText = titleObj:getText()
    local allRulesData = p._internal_fetchAllRules(pageTitleString)

    if not allRulesData then
        return (outputType == 'context') and titleText or ''
    end

    -- 处理 outputType = 'context'
    if outputType == 'context' then
        if not frame then
           -- 移除 mw_html 包装
           return '<span class="error">错误:type=\'context\' 需要 frame 对象。</span>'
        end
        if allRulesData.title and allRulesData.title ~= '' then
            local rule_wikitext = "-{T|" .. allRulesData.title .. "}-"
            local success_preprocess, result = pcall(frame.preprocess, frame, rule_wikitext)
            if success_preprocess then
                return result
            else
                mw.log('ConversionRuleExtractor: frame:preprocess failed for T rule on page ' .. pageTitleString .. ': ' .. tostring(result))
                -- 移除 mw_html 包装
                return '<span class="error">处理T规则时出错。</span>'
            end
        else
            local applicableRules = {}
            if allRulesData['local'] then
                for _, rule in ipairs(allRulesData['local']) do table.insert(applicableRules, rule) end
            end
            local allGroupRules = {}
            if allRulesData.groups then
                for _, groupInfo in ipairs(allRulesData.groups) do
                    if groupInfo.rules then
                        for _, rule in ipairs(groupInfo.rules) do table.insert(allGroupRules, rule) end
                    end
                end
            end
            local filteredGroupRules = filterGroupRulesByText(allGroupRules, titleText)
            for _, rule in ipairs(filteredGroupRules) do table.insert(applicableRules, rule) end

            if #applicableRules == 0 then
                return titleText
            else
                local rules_wikitext = formatRules(applicableRules, 'H')
                local success_preprocess, result = pcall(frame.preprocess, frame, rules_wikitext .. titleText)
                 if success_preprocess then
                    return result
                else
                    mw.log('ConversionRuleExtractor: frame:preprocess failed for H rules on page ' .. pageTitleString .. ': ' .. tostring(result))
                    -- 移除 mw_html 包装
                    return '<span class="error">应用H规则时出错。</span>'
                end
            end
        end
    else
        -- 处理格式化输出 (非 context)
        local combinedRules = {}
        -- 修正:确保 T 规则被正确添加
        if allRulesData.title and allRulesData.title ~= '' then
             table.insert(combinedRules, allRulesData.title)
        end
        -- 添加本地规则
        if allRulesData['local'] then
            for _, rule in ipairs(allRulesData['local']) do table.insert(combinedRules, rule) end
        end
        -- 添加过滤后的组规则
        local allGroupRules = {}
        if allRulesData.groups then
            for _, groupInfo in ipairs(allRulesData.groups) do
                if groupInfo.rules then
                    for _, rule in ipairs(groupInfo.rules) do table.insert(allGroupRules, rule) end
                end
            end
        end
        local filteredGroupRules = filterGroupRulesByText(allGroupRules, titleText)
        for _, rule in ipairs(filteredGroupRules) do table.insert(combinedRules, rule) end

        -- 现在调用 formatRules
        return formatRules(combinedRules, flag)
    end
end

--[[--------------------------< 模板入口点 >--------------------------]]
function p.getFullText(frame)
    local args = Arguments.getArgs(frame)
    local page = args[1] or args.page
    local flag = args.flag -- 保持默认由 formatRules 处理 (nil -> 'H')

    if not page or page == '' then
        -- 移除 mw_html 包装
        return '<span class="error">错误:必须提供页面标题。</span>'
    end
    -- 注意:getFullText 不处理 type 参数
    local result = p.getFullTextRules(page, flag)
    return result
end

function p.getTitle(frame)
    local args = Arguments.getArgs(frame)
    local page = args[1] or args.page
    local flag = args.flag
    local outputType = args.type

    if not page or page == '' then
         -- 移除 mw_html 包装
         return '<span class="error">错误:必须提供页面标题。</span>'
    end
    local result = p.getTitleRules(page, flag, outputType, frame)
    return result
end

return p