Modulo:Fumetto e animazione/sandbox: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
correggo
Omega Bot (discussione | contributi)
m Bot: rimuovo no globals obsoleto
 
(48 versioni intermedie di un altro utente non mostrate)
Riga 3:
le funzioni di categorizzazione automatica
]]
 
require('strict')
 
local cfg = mw.loadData("Modulo:Fumetto e animazione/Configurazione/sandbox")
local getArgs = require('Module:Arguments').getArgs
local error_category = 'Errori di compilazione del template Fumetto e animazione'
 
Riga 11 ⟶ 13:
-- =============================================================================
 
-- Converte la lettera iniziale di una stringa in maiuscola
-- Restituisce i valori di una tabella di alias nella configurazione
local function build_reverse_aliasucfirst(table_namestr)
return str:gsub('^%l', string.upper)
local reverse_alias = {}
for alias, name in pairs(cfg['alias_' .. table_name]) do
if not reverse_alias[name] then reverse_alias[name] = {} end
table.insert(reverse_alias[name], alias)
end
return reverse_alias
end
 
-- Restituisce un valore senza eventuale wikilink a inizio stringa
local function delink(value)
if not value then return end
local pattern
if value:find('|') then
Riga 29 ⟶ 27:
pattern = "^'*%[%[ *([^%[%]]-) *%]%]"
end
return ucfirst(value:match(pattern) or value)
end
 
-- Restituisce listeun numero variabile di valori uno alla volta
local function extract_values(args, base_name)
local index = 0
return function()
whileindex true= doindex + 1
local value = args[base_name .. ' ' .. tostring(index)]
index = index + 1
localif not value =and args[base_nameindex ..== '1 ' .. tostring(index)]then
if not value and index == 1 thenargs[base_name]
value = args[base_name]
end
if not value then break end
return delink(value)
end
return value
end
end
 
-- Restituisce un numero variabile di generi uno alla volta
-- Converte la lettera iniziale di una stringa in minuscola
local function lcfirstextract_genres(strvalue)
local index = 0
return str:gsub('^%u', string.lower)
local substrings = mw.text.split(value, ' *, *')
return function()
index = index + 1
if not substrings[index] then return end
local genre
local link, tail = substrings[index]:match('^(%[%[.-%]%]%a*)(.*)$')
if link then
genre = link:gsub('^%[%[', ''):gsub('^[^%[%]%|]+%|', ''):gsub('%]%]', '')
else
genre, tail = substrings[index]:match('^([%w%(%) ]+[%w%(%)])( *.*)$')
end
if genre then
genre = mw.text.trim(genre:lower())
end
return cfg.alias_genere[genre] or genre, tail, substrings[index]
end
end
 
-- Parsifica i parametri rimuovendo le stringhe vuote
local function parse_args(args)
local ret = {}
for key, value in pairs(args) do
if value and= mw.text.trim(value)
if =value ~= '' then
argsret[key] = nilvalue
end
end
return argsret
end
 
-- Sostituisce le parentesi in una stringa coi corrispondenti codici ascii
local function replace_braces(s)
local new_s = mw.ustring.gsub(s, "%[", "[")
new_s = mw.ustring.gsub(new_s, "%]", "]")
new_s = mw.ustring.gsub(new_s, "%(", "(")
new_s = mw.ustring.gsub(new_s, "%)", ")")
new_s = mw.ustring.gsub(new_s, " ", " ")
return new_s
end
 
Riga 84 ⟶ 87:
setmetatable(self, { __index = Media })
 
self.tipoargs = args.tipo
self.sottotipotipo = args.sottotipoself:_getType()
self.sottotipo = self:_getSubtype()
self.name = self:_getName()
self.alias = self:_getAlias()
Riga 110 ⟶ 114:
function Media:_getName()
return self:_getValue('tipo', 'sottotipo')
end
 
-- Verifica che il sottotipo di medium sia riconosciuto
function Media:_getSubtype()
if cfg.sottotipo[self.tipo] and cfg.sottotipo[self.tipo][self.args.sottotipo] then
return self.args.sottotipo
end
end
 
-- Verifica che il tipo di medium sia riconosciuto
function Media:_getType()
if cfg.tipo[self.args.tipo] or cfg.sottotipo[self.args.tipo] then
return self.args.tipo
end
end
 
-- Cerca il nome o l'alias del medium nella configurazione
function Media:_getValue(key_tipotype_table_name, key_sottotiposubtype_table_name)
local ret =return cfg[key_sottotiposubtype_table_name][self.tipo] and
cfg[key_sottotiposubtype_table_name][self.tipo][self.sottotipo] or
cfg[key_tipotype_table_name][self.tipo]
return ret and lcfirst(ret) or nil
end
 
Riga 131 ⟶ 148:
setmetatable(self, { __index = CategoryManager })
 
self.args = parse_args(args)
self.media = Media:new(self.args)
self.error_category = false
self.year = self:_getYear()
self.genre_table_name = self:_getGenreTableName()
self.categories = {}
self.tables_matched = {}
 
self:_addCategories(self.args.categorie == 'no')
 
return self
Riga 148 ⟶ 167:
 
-- Avvia la categorizzazione automatica dell'opera
function CategoryManager:_addCategories(error_only)
if self.genre_table_name then
if (self.args['data inizio'] or self.args['data fine']) and not self.year then
self:_addCategory_addCategoriesBy(error_category'genere')
end
 
if error_only then return end
 
if self.media.name == "serie televisive d'animazione" then
Riga 160 ⟶ 177:
:_addCategoriesBy('paese', 'fp', self._categorizeTVSeriesByCountry)
elseif self.media.name == "film d'animazione direct-to-video" then
self:_addCategoriesBy('paese', 'mp', self._categorizeDTVFilmByCountry)
self
:_addCategory(self.media.name)
:_addCategoriesBy('paese', 'mp', self._categorizeDTVFilmByCountry)
elseif self.media.name == "webserie d'animazione" then
self:_addCategoriesBy('paese', 'fp', self._categorizeWebseriesByCountry)
Riga 171 ⟶ 186:
:_addCategoriesBy('editore_manga')
:_addCategoriesBy('editore')
:_addCategoriesBy('target', nil, self.ucfirst)
elseif self.media:inArray('manhua', 'manhwa') then
self:_addCategoriesBy('editore')
Riga 180 ⟶ 195:
:_addCategoriesBy('etichetta')
:_addCategoriesBy('editore')
elseif self.media.tipo == 'fumetto' and self.media.name ~= 'fumetti'sottotipo then
self
:_addCategoriesBy('etichetta_sottotipo', nil, self._prependSubtype_substituteParameter)
:_addCategoriesBy('etichetta')
:_addCategoriesBy('editore_sottotipo', nil, self._prependSubtype_substituteParameter)
:_addCategoriesBy('editore')
:_addCategoriesBy('paese', 'mp', self._categorizeComicByCountry)
Riga 201 ⟶ 216:
self:_addCategoriesBy('studio')
local broadcaster
local network = self.args['rete 1'] or self.args.rete
if self.media:inArray('film TV', 'serie TV') then
local networkbroadcaster = self.args[:_getCategory(network, 'rete 1'] or self.args.rete)
elseif network and self.media:inArray('ONA', 'webserie') then
broadcaster = self:_getCategory(delink(network), 'rete')
elseif self.media.aliaserror_category == 'webserie' thentrue
end
if not network and self.media:inArray('film TV', 'ONA', 'serie TV', 'webserie') then
local platform = self.args['streaming 1'] or self.args.streaming
broadcaster = self:_getCategory(delink(platform), 'streaming')
end
if broadcaster then
self:_addCategory(mw.message.newRawMessage(broadcaster, self.media.alias .. ' ' .. broadcaster):plain())
end
end
 
-- categorizzazione per tipo delle opere non suddivise per anno
if self.media:inArray('film direct-to-video', 'manhua', 'manhwa', 'ONA', 'webserie') then
self:_addCategory(self.media.name)
-- categorizzazione delle opere suddivise per anno
elseif self.yearmedia.name and self.media.sottotipo ~= 'film direct-to-video'year then
local media = self.media.namesottotipo ~= 'serie televisive animeTV' and
self.media.alias or self.media.name
self:_addCategory(string.format('%s del %s', media, self.year))
end
 
if self.error_category == true then
self:_addCategory(error_category)
end
end
Riga 226 ⟶ 248:
-- Aggiunge categorie per una lista di valori
function CategoryManager:_addCategoriesBy(table_name, gender, callback)
local base_name = table_name:match('[^_]+')
if self:_isCategoryRedundant(table_name) == false then
for value in extract_values(self.args, base_name) do
local base_name = table_name:match('[^_]+')
if table_name == 'genere' then
for value in extract_values(self.args, base_name) do
self:_addCategoryByGenre(value)
if table_name == 'paese' then
elseif table_name == 'paese' then
self:_getCategoryByCountry(value, gender, callback)
self:_addCategoryByCountry(value, gender, callback)
else
elseif self:_isCategoryRedundant(table_name) == false then
if callback then value = callback(self, value) end
local category = self:_getCategory(value, table_name)
if category then
if callback then
self.tables_matched[table_name] = true
self:_addCategorycategory = callback(self, category)
end
self.tables_matched[table_name] = true
self:_addCategory(category)
end
end
Riga 246 ⟶ 270:
-- Formatta e aggiunge una categoria
function CategoryManager:_addCategory(category)
if self.args.categorie ~= 'no' or category == error_category then
table.insert(self.categories, string.format('[[Categoria:%s]]', category))
table.insert(self.categories, string.format('[[Categoria:%s]]', category))
end
return self
end
 
-- Aggiunge la categoria per Paese dopo aver individuato l'aggettivo
-- maschile o femminile, singolare o plurale adeguato
function CategoryManager:_addCategoryByCountry(country, gender, callback)
local frame = mw.getCurrentFrame()
local success, adj = pcall(frame.expandTemplate, frame, {
title = 'Template:AggNaz/' .. delink(country),
args = { gender }
})
if not success then
self.error_category = true
elseif self:_isCategoryRedundant('paese') == false then
callback(self, adj)
end
end
 
-- Aggiunge una o più categorie per genere dell'opera
function CategoryManager:_addCategoryByGenre(value)
for genre in extract_genres(value) do
if cfg.genere_wikilink[genre] then
local categories = cfg[self.genre_table_name][genre]
if categories then
for _, category in ipairs(categories) do
self:_addCategory(category)
end
end
else
self.error_category = true
end
end
end
 
Riga 287 ⟶ 344:
-- Cerca il nome di una categoria nella configurazione
function CategoryManager:_getCategory(key, table_name)
key = delink(key)
key = cfg['alias_' .. table_name] and cfg['alias_' .. table_name][key] or key
return cfg[table_name][key]
end
 
-- Individua la tabella dei generi idonei al tipo di opera nella configurazione
-- Restituisce la categoria per Paese se presente l'aggettivo adeguato
function CategoryManager:_getCategoryByCountry_getGenreTableName(value, gender, callback)
local table_name
local adjective = self:_getCountryAdjective(value, gender)
if self.media:inArray('anime', 'manga') then
if adjective then
table_name = 'genere_animanga'
return callback(self, adjective)
elseif self.media.tipo == 'light novel' then
table_name = 'genere_light_novel'
elseif self.media:inArray('fumetto', 'manhua', 'manhwa') then
table_name = 'genere_fumetto'
end
return table_name
end
 
-- Ottiene l'aggettivo maschile o femminile, singolare o plurale per un dato Paese
function CategoryManager:_getCountryAdjective(country, gender)
local frame = mw.getCurrentFrame()
local success, result = pcall(frame.expandTemplate, frame, {
title = 'Template:AggNaz/' .. country,
args = { gender }
})
if success then return result end
end
 
-- Ricava l'anno dell'opera dalle date di inizio e fine
function CategoryManager:_getYear()
if not (self.args['data inizio'] or self.args['data fine']) then return end
local start_date = self.args['data inizio'] or ''
local end_date = self.args['data fine'] or ''
returnlocal year = (start_date .. ' ' .. end_date):match('%f[%w]%d%d%d%d%f[%W]')
if year then
return year
else
self.error_category = true
end
end
 
Riga 328 ⟶ 387:
end
 
-- AnteponePopola il sottotipo delll'operaargomento anumerato in una stringa col tipo dell'opera
function CategoryManager:_prependSubtype_substituteParameter(valuemsg)
return selfmw.mediamessage.sottotiponewRawMessage(msg, self.media. valuename):plain()
end
 
-- Converte la lettera iniziale di una stringa in maiuscola
function CategoryManager:ucfirst(str)
return str:gsub('^%l', string.upper)
end
 
Riga 344 ⟶ 398:
local p = {}
 
-- Funzione per il template FeA, categorizza trannela che per generevoce
function p.categorie(frame)
if mw.title.getCurrentTitle().namespace ~= 0 then return end
returnlocal CategoryManager:newargs = parse_args(frame:getParent().args):listCategories()
return CategoryManager:new(args):listCategories()
end
 
-- Funzione per il template FeA, elabora categorie ei wikilink dei generi
function p.generi(frame)
local ret = {}
local args = getArgs(frame, {parentOnly = not frame.args[1]})
local genreargs = parse_args(frame.args[1])
iffor genre, ==tail, ''default thenin returnextract_genres(args[1]) enddo
local wikilink = cfg.genere_wikilink[genre]
local current_page = mw.title.getCurrentTitle()
table.insert(ret, wikilink and (wikilink .. tail) or default)
local current_namespace = current_page.namespace
local category
local result = {}
for name, alias_name in pairs(cfg['alias_genere']) do
local piped = mw.ustring.match(genre, '%[%[[^%[]*|%s*' .. name .. '%s*%]%]')
local pattern = (piped and '%[%[[^%[]*|%s*' or '%[%[%s*') .. name .. '%s*%]%]%a*'
genre = mw.ustring.gsub( genre, pattern, '[[' .. alias_name .. ']]' )
end
return table.concat(ret, ', ')
for name, correct_name in pairs(cfg['genere']) do
if current_namespace == 0 and args.categorie ~= 'no' then
local tipo = {
['anime'] = correct_name[1],
['fumetto'] = correct_name[2],
['light novel'] = correct_name[3],
['manga'] = correct_name[1],
['manhua'] = correct_name[2],
['manhwa'] = correct_name[2]
}
tipo = tipo[args.tipo]
tipo = tipo and tipo[1] and tipo[1] .. ']][[Categoria:' .. tipo[2] or tipo
category = tipo and tipo ~= '' and '[[Categoria:' .. tipo .. ']]'
end
local piped = mw.ustring.match(genre, '%[%[[^%[]*|%s*' .. name .. '%s*%]%]')
local pattern = (piped and '%[%[[^%[]*|%s*' or '%[%[%s*') .. name .. '%s*%]%]%a*'
genre = mw.ustring.gsub( genre, pattern, correct_name[4] .. (category or '') )
-- Categoria d'errore in caso di genere senza corrispondenza
local list = mw.text.split( genre, ',' )
for i = 1, #list do
local s = replace_braces(list[i])
local p = replace_braces(correct_name[4])
if mw.ustring.match( s, p ) then
result[i] = ''
elseif result[i] == nil and current_namespace == 0 then
result[i] = '[[Categoria:' .. error_category .. ']]'
end
end
end
genre = genre .. table.concat(result)
return genre
end
 
-- Funzione per il manuale, restituiscemostra lal'elenco configurazionedi per aziendevalori e targetrispettivi alias per
-- una data tabella nella configurazione
function p.tabella_configurazione(frame)
local argstable_name = getArgsparse_args(frame.args)[1]
if not cfg[table_name] then return end
local table_name = args[1]
if not(table_name) then return '' end
local reverse_alias = build_reverse_alias(table_name)
local root = mw.html.create('table')
root
:addClass('wikitable mw-collapsible mw-collapsed sortable')
:tag('tr')
:tag('th'):wikitext(table_name'Valore'):done()
:tag('th'):wikitext('Alias'):done()
:tag('th'):wikitext('CategoriaRisultato'):done()
local keys, reverse_alias = {}, {}
for name, cat_name in pairs(cfg[table_name]) do
local name_codealias_table_name = table_name:find('genere') ==and 'genere' andor table_name
for alias, name in pairs(cfg['alias_' .. alias_table_name] or {}) do
replace_braces(cat_name[4]) or
if not reverse_alias[name] then reverse_alias[name] = {} end
'[[' .. name .. ']]'
table.insert(reverse_alias[name], alias)
local cat_code = {}
end
if cat_name[1] then
for key in pairs(cfg[table_name]) do table.insert(keys, key) end
for i, cat in ipairs(cat_name) do
table.sort(keys)
if i > 3 then break end
local pre_table_name
cat = cat[1] and
if table_name == 'editore_sottotipo' or table_name == 'etichetta_sottotipo' then
cat[1] .. ']]<br />[[:Categoria:' .. cat[2] or cat
pre_table_name = cfg.sottotipo.fumetto
if cat ~= '' then
elseif table_name == 'rete' or table_name == 'streaming' then
cat_code[#cat_code+1] = '[[:Categoria:' .. cat .. ']]'
pre_table_name = cfg.alias_sottotipo.cartone
end
end
for _, key in ipairs(keys) do
local result, values = {}, {}
reverse_alias[key] = reverse_alias[key] or {}
if pre_table_name then
for _, subtype in pairs(pre_table_name) do
local msg = cfg[table_name][key]
subtype = ucfirst(subtype)
table.insert(values, mw.message.newRawMessage(msg, subtype):plain())
end
elseif type(cfg[table_name][key]) == 'string' then
cat_code = table.concat(cat_code, '<br />')
values = { cfg[table_name][key] }
else
values = cfg[table_name][key]
cat_code = '[[:Categoria:' .. cat_name .. ']]'
end
for _, str in ipairs(values) do
local alias_code = '&nbsp;'
if reverse_alias[name]table_name ~= 'genere_wikilink' then
str = string.format('[[:Categoria:%s]]', str)
for i, alias in ipairs(reverse_alias[name]) do
reverse_alias[name][i] = '&#91;&#91;' .. alias .. '&#93;&#93;'
end
alias_code = table.concatinsert(reverse_alias[name]result, '<br />'str)
end
table.sort(result)
result = table.concat(result, '<br />')
table.sort(reverse_alias[key])
reverse_alias[key] = table.concat(reverse_alias[key], '<br />')
root:tag('tr')
:tag('td'):wikitext(name_codekey):done()
:tag('td'):wikitext(alias_codereverse_alias[key]):done()
:tag('td'):wikitext(cat_coderesult):done()
end
return tostring(root)