Ir al contenido

Módulo:Proofreadpage index template

De Wikisource, la biblioteca libre.
Documentación del módulo


Uso

Módulo que construye la información visible de un Índice (Index).

El módulo está pensado para ser llamado por MediaWiki:Proofreadpage index template, pero puede ser probado con el siguiente código:

{{#invoke:Proofreadpage index template|fields|parámetros}}

  • fields es la función del módulo encargada de construir la página, según el resto de parámetros.
  • Parámetros:
  • Wikidata (obligatorio): es el identificador de Wikidata del Índice. Por ejemplo, «Q107297266». A partir de éste se capturan de Wikidata los datos del Índice "capturables", como Autor, Traductor, Titulo, etc. Más información en Ayuda:Índices.
-Si un campo está informado a mano se ignorará lo que se hubiera capturado de Wikidata.
-Si un campo no está informado a mano y se recupera algún dato de Wikidata, entonces se mostrará este último.
-Si un campo no está informado a mano y no se recupera nada de Wikidata, el campo no aparecerá.
  • NomPag (obligatorio): es el {{NOMPAGE}} de la página del Índice. Para hacer pruebas podemos poner el nombre del archivo, como «El Robinson suizo (1864).pdf». Se utiliza para mostrar la imagen del archivo así como el enlace para purgar las páginas.
  • NomPagE (obligatorio): es el {{NOMPAGEE}} de la página del Índice. Para hacer pruebas podemos poner el nombre del archivo, como «El_Robinson_suizo_(1864).pdf». Se utiliza para mostrar la imagen del archivo.

Ejemplo

  • Código mínimo de pruebas que captura datos de Wikidata: {{#invoke:Proofreadpage index template|fields|NomPag=El Robinson suizo (1864).pdf|NomPagE=El_Robinson_suizo_(1864).pdf|Paginas=test|Wikidata=Q107297266}}
Esta documentación está transcluida desde Módulo:Proofreadpage index template/doc.
Los editores pueden experimentar en la zona de pruebas
Por favor, añade las categorías a la subpágina de documentación.
(subpáginas - enlaces)

--------------------------------------------------------------------------------
-- Adaptado de https://en.wikisource.org/wiki/Module:Proofreadpage_index_template
--           y https://ca.wikisource.org/wiki/Module:Proofreadpage_index_template
-- This is a module to implement logic for [[MediaWiki:Proofreadpage index template]]
--------------------------------------------------------------------------------
-- Ejemplo (función p.fields):
-- {{#invoke:Proofreadpage index template|fields|NomPag=El Robinson suizo (1864).pdf|Paginas=tabla|Wikidata=Q107297266}}
--------------------------------------------------------------------------------

local Wikidata = require('Module:Wikidata')
local Obra = require('Módulo:Obra')
local getArgs = require('Module:Arguments').getArgs
local cats = require('Módulo:Categorías')
local wTitulo = mw.title.getCurrentTitle()	--Nombre sin "Índice:"
local p = {}

-- mapping of field ID to field properties
local headings = {
	
	title		=	{	txt = 'Título', index='Titulo', p='P1476'},
	subtitle	=	{	txt = 'Subtítulo', index='Subtitulo', p='P1680'},
	serie		=	{	txt = 'Serie o colección', index='Serie', p='P361'}, --P361:"forma parte de"
	volume		=	{ 	txt = 'Volumen', index='Volumen', p='P478'},
	
	author		=	{	txt = 'Autor', emblem = '[[Archivo:Commons-emblem-notice.svg|20px|alt=|frameless|link=Ayuda:Autores]]',	
						index = 'Autor', p='P50' },
	editor		=	{	txt = 'Editor',	index='Editor', p='P98'},
	illustrator =	{	txt = 'Ilustrador', index='Ilustrador', p='P110'},
	translator	=	{	txt = 'Traductor',	index='Traductor', p='P655'},
	introducer  =   {   txt = 'Prologuista', index='Prologuista', p='P2679'},
	
	year		=	{	txt = 'Año', index='Ano', p='P577'},
	editorial	=	{	txt = 'Editorial', emblem='[[Archivo:Commons-emblem-notice.svg|20px|alt=|frameless|link=Portal:Imprentas_y_editoriales]]',
						index='Editorial', p='P123'},
	printer 	=	{	txt = 'Imprenta', emblem='[[Archivo:Commons-emblem-notice.svg|20px|alt=|frameless|link=Portal:Imprentas_y_editoriales]]', 
						index='Imprenta', p='P872'},
	place		=	{	txt = 'Lugar', index='Lugar', p='P291'},
	country		=	{	txt = 'País', emblem='[[Archivo:PD-icon.svg|20px|alt=|frameless|link=Wikisource:Derechos_de_autor]]', 
						index = 'derechos'},	--derechos (P495) pasar a Wikidata realmente?
	editionof   =   {   txt = 'Obra', index='Obra', p='P629'},
	
	source		=	{	txt = 'Fuente', emblem='[[Archivo:Commons-emblem-notice.svg|20px|alt=|frameless|link=Wikisource:Recursos_libres]]',
						index= 'Fuente'},
	modernizar	=	{	txt = 'Modernización de la ortografía', emblem='[[Archivo:Commons-emblem-notice.svg|20px|alt=|frameless|link=Wikisource:Modernización_de_textos]]',	
						index='Modernizacion'},
	quality 	=	{	txt = 'Progreso', index='Progreso'},
	wikidata	=	{	txt = 'Metadatos', index='Wikidata'},
	
}
local function asterisco(color, titulo)
	return " <span style='color:"..color.."; font-size:75%;' title='"..titulo.."'>*</span>"
end
local function aCadena(id, obj)
	if type(obj) == 'string' then
		if obj == 'valor desconocido' then
			if id == 'translator' or id =='illustrator' or id == 'editor' or id == 'introducer' 
			or id == 'editorial' or id == 'printer' or id == 'serie' or id == 'editionof' then
				obj = 'Anónimo'
			elseif id == 'author' then
				obj = '[[:Categoría:Obras de autores anónimos|Anónimo]]'
			end
		end
		return obj
	
	elseif type(obj) == 'table' then
		if obj.text then return aCadena(id, obj.text) end
		
		local result = {}
		for k, v in pairs(obj) do
			table.insert(result, aCadena(id, v))
		end
		return mw.text.listToText(result)
	end
	
end

local function construct_image(content, c)
	if c.nompage == nil or c.nompage == '' then error('nompage no puede ser nulo') end
	local s = ''

	--Miramos si en WD hay 1 o más P996, capturamos el que coincida, y le miramos el P4714 (nº pág. con título).
	local P4714 = ''
	if c.qid then
		for _, file in pairs( c.commonsFile.WD ) do
			if mw.text.decode(c.commonsFile.WS) == mw.text.decode(file) then	--decode por si apóstrofe llega como "&#39;"
				P4714 = Wikidata.claim{item=c.qid, property="P996", qualifier="P4714", lang="es", list=false}
			end
		end
	end	

	s = s .. '<tr><td valign="top">'
	if content then
	else
		if P4714 == '' then
			content = '1'	--si no hay nada de nada
		else
			content = P4714
		end
		if content == nil then content = '1' end
	end
	if tonumber(content) == nil then
		s = s .. content
	else
		s = s .. '<span id="ws-cover" style="display:none; speak:none;">'
		s = s .. c.nompage .. "/" .. content .. "</span>"
		s = s .. '[[File:' .. c.nompage .. '|page=' .. content .. '|frameless]]'
	end
	s = s .. '</td>'
	s = s .. '<td valign="top"><table style="margin-left:0">'	--se cierran en construct_field_paginas
	return s
end

local function construct_field_paginas(content, c)

	if c.nompage == nil or c.nompage == '' then return "Error en construct_field_pagines (nompage)" end
	if content == nil or content == '' then return "Error en construct_field_pagines (content)" end
	local s = ''
	s = s .. '</table></td></tr>'
	s = s .. '<tr><td valign="top" colspan="2"><span class="plainlinks">'
	s = s .. '<b>[//es.wikisource.org/wiki/File:' .. c.nompage .. '?action=purge Páginas]</b></span>'
	s = s .. ' ([[Ayuda:Nivel_de_las_páginas|Nivel]])\n'
	s = s .. '<div style="padding-left:0.5em; background-color:#F0F0F0; color:black;">\n' .. content .. '</div></td></tr>'
	s = s .. '</table></td>'
	return s
end

local function construct_field_sumario(content)
	local s = ''
	if content then
		s = '<td width="33%" valign="top">' .. content .. '</td>'
	end
	return s
end
local function getBadge( qid )
	local badges = Wikidata.badge{args={qid=qid, raw=true}}
	if #badges > 0 then
		for k, v in pairs(badges) do
			if v then return v end
		end
	end
end
local function consolidado(args, obra)
	local c = {}
	
	c.qid = obra.qid
	
	for id in pairs(headings) do
		local idx = headings[id]
		c[id] = {}
		if idx.index then  --toma datos del índice
			c[id].WS = args[idx.index]
		end
		if c.qid then --tiene propiedad en Wikidata
			c[id].WD = aCadena(id, obra[id])
		end
		-- content: prioridad WS
		c[id].content = c[id].WS or c[id].WD
	end
	c.commonsFile = {WD = obra.commonsFile, WS = args.NomPag}
	c.nompage =  mw.uri.encode( args.NomPag, 'WIKI' )

	return c
end

-- construct a basic "field" row
local function construct_field(id, c)
	if id == nil then error( "Error en construct_field" ) end
	local qid = c.qid
	local P = headings[id].p
	local emblem = headings[id].emblem
	local title = headings[id].txt
	local idx = c[id]
	local content = idx.content
	local CatError = "[[Categoría:Índices con discrepancias respecto a Wikidata"	
	local siWDsiWS = idx.WD and idx.WS --hay contenido en WD y en WS (se puede borrar)
	local noWDsiWS = not idx.WD and idx.WS	--no hay contenido en WD pero sí en WS (no borrar hasta migrarlo a WD)
	local siWDnoWS = idx.WD and not idx.WS
	local eqWDWS = siWDsiWS and idx.WD == idx.WS
	local caterror = false  --campo generó error
	
	if id == 'title' then
		if not idx.WS then
			local wSiteLink = mw.wikibase.getSitelink(qid or '')
			if wSiteLink then
				if idx.WD then
					content = "''[[" .. wSiteLink .. "|" .. idx.WD .. "]]''"
				else
					content = "''[[" .. wSiteLink .. "]]''"
				end
			elseif idx.WD then
				content = "''[["..idx.WD.."]]''"	
			end
		end
	end

	if id == 'modernizar' then
		if content then
			if content == 'S' then
				content = '[[Wikisource:Modernización de textos|Ortografía antigua — El lector puede elegir modernizar la ortografía]]'
			else
				content = '[[Wikisource:Modernización de textos|No modernizar]]'
			end
		end
	end

	if id == 'source' then
		if content == nil then
			if c.commonsFile.WS == nil then
				content = CatError .. "|Nompag]]"
				caterror = 'ERROR: Nompag'
			else	--todo: se podría buscar los identificadores de Wikidata P675 (GB), P724 (IA), etc.
				content = "[[:File:" .. c.commonsFile.WS .. "|Archivo]]"
				cats:addCat('Índices sin fuente')
			end
		else
			-- revisar: en general la fuente la explicitamos localmente con una plantilla
			-- tenemos que trackear si está en Wikidata? cual propiedad?
			-- noWDsiWS = true
		end
	end

	if id == 'wikidata' then
		if content == nil then
			cats:addCat('Índices no conectados a Wikidata')
			return ""
		end
		content = "[[File:Wikidata-logo.svg|20px|link=d:" .. content .. "]] [[d:" .. content .. "|" .. content .. "]]"
		if mw.wikibase.entityExists(qid) == false then
			content = content .. CatError .. "|Qid]]"
			caterror = 'ERROR: QID NO EXISTE'
		end
		if not c.commonsFile.WD then
			if wTitulo.text then
				local wArchivo = mw.title.new( wTitulo.text, 'File' )
				if wArchivo.exists then
					--Archivo no está en Commons pero sí localmente en Wikisource (casos excepcionales)
				else
					--No hay archivo local ni P996: hay que añadirlo (archivo en Commons) al ítem en Wikidata.
					content = content .. CatError .. "|Commons]]"
					caterror = 'ERROR: SIN P996 (archivo en Commons)'
				end
    		else
				content = content .. CatError .. "|Error]]"
				caterror = 'ERROR: SIN TEXTO EN ÍNDICE'
			end
		elseif c.commonsFile.WS then
			local FileMatch
			for _, file in pairs( c.commonsFile.WD ) do
				if mw.text.decode(c.commonsFile.WS) == mw.text.decode(file) then	--decode por si apóstrofe llega como "&#39;"
					FileMatch = file
				end
			end
			if not FileMatch then
				content = content .. CatError .. "|Fichero]]"
				caterror = 'ERROR: P996 REFIERE OTRO FICHERO'
			end
		end
	end	
	
	if id == 'quality' then
		local badges = {
			C = "Q20748091", P = "Q20748091",
			V = "Q20748092", T = "Q20748093",
			L = "Q20748094", E = "Q20748094"}
		local badge_WS = badges[content]
		
		if qid then	
			local badge_WD = getBadge(qid)
			if badge_WD then	
				if badge_WD == "Q20748091" then content = "C" end
				if badge_WD == "Q20748092" then content = "V" end
				if badge_WD == "Q20748093" then content = "T" end
				if badge_WD == "Q20748094" then content = "L" end
				
				if badge_WS ~= badge_WD then
					-- Todo: manejar discrepancia 
				end	
			else
				-- if content then noWDsiWS = true end
			end
		end
		-- prioridad local
		if idx.WS and idx.WS ~= '' then
			content = idx.WS
		end
		if content == nil then
			content = "[[:Categoría:Índices con progreso desconocido|Progreso desconocido]]"
			cats:addCat('Índices con progreso desconocido')
		elseif content == 'C' then
			content = "[[:Categoría:Índices no corregidos|Por corregir]]"
			cats:addCat('Índices no corregidos')
		elseif content == 'P' then
			content = "[[:Categoría:Índices sin pagelist|Por corregir - pendiente crear <nowiki><pagelist/></nowiki>]]"
			cats:addCat('Índices no corregidos')
			cats:addCat('Índices sin pagelist')
		elseif content == 'V' then
			content = "[[:Categoría:Índices corregidos|Corregido — Todas las páginas corregidas pero no todas validadas]]"
			cats:addCat('Índices corregidos')
		elseif content == 'T' then
			content = "[[:Categoría:Índices validados|Terminado — Todas las páginas validadas]]"
			cats:addCat('Índices validados')
		elseif content == 'L' then
			content = "[[:Categoría:Índices dañados|Archivo fuente debe ser arreglado antes de corregirlo]]"
			cats:addCat('Índices dañados')
		elseif content == 'E' then
			content = "[[:Categoría:Índices en extractos|Extracto]]"
			cats:addCat('Índices en extractos')
		else
			content = "[[:Categoría:Índices con progreso desconocido|Progreso desconocido]]"
			cats:addCat('Índices con progreso desconocido')
		end
	end	
	-- categorías de seguimiento
	if id == 'editionof' then 
		if content == nil or content == '' then
			cats:addCat('Índices sin obra asociada')
			return ''
		else
			cats:addCat('Índices con obra asociada')
		end
	end
	-- parámetros que no deben pasar a Wikidata
	if not P or id == 'serie' or not qid or qid == '' then
		noWDsiWS = false
	end	
	if content == nil or content == '' then
		return ''
	end
	
	if siWDnoWS == true then
		local lapiz = ' <span class="penicon" data-bridge-edit-flow="single-best-value">'
				.. "[[File:Arbcom ru editing.svg|10px|baseline|"
				.. string.gsub(mw.message.new('Wikibase-client-data-bridge-bailout-suggestion-go-to-repo-button'):inLanguage("es"):plain(), '{{WBREPONAME}}', 'Wikidata')
		if id == 'title' then
			content = content .. lapiz	.. "|link=https://www.wikidata.org/wiki/" .. qid .. "?uselang=es#sitelinks-wikisource]]</span>"
		else
			if P and P ~= '' then
				content = content .. lapiz .. "|link=https://www.wikidata.org/wiki/" .. qid .. "?uselang=es#" .. P .. "]]</span>"
			end
		end
	end
	if eqWDWS then
		cats:addCat('índices con datos duplicados en Wikidata')
		title = title .. asterisco('blue', 'Datos duplicados en Wikidata')
	elseif siWDsiWS then
		cats:addCat('Índices con datos en Wikidata')
		title = title .. asterisco('blue', 'Datos en Wikidata')
	end
	if noWDsiWS then
		cats:addCat('índices con datos para Wikidata')
		title = title .. asterisco('green', 'Datos para Wikidata')
	end
	if caterror and caterror ~= '' then
		title = title .. asterisco('red', caterror)
	end
	
	local s = ''
	s = s .. '\n<tr>'
	s = s .. '<td valign="top">' .. (emblem or '') .. '</td>\n'
	s = s .. '<th valign="top" align="left"><b>' .. title .. '</b></th>\n'
	s = s .. '<td>' .. content .. '</td>\n'
	s = s .. '</tr>\n'
	return s
end

function p.fields(frame)	
	local args = getArgs(frame)
	local obra = Obra.newWork(args.Wikidata)
	local c = consolidado(args, obra)

	local s = ""
	
	s = s .. '<table width="100%"><tr><td valign="top"><table>'
	s = s .. construct_image(args['Imagen'], c)

	-- Tras la imagen, intentamos mostrar una fila por campo (si no hay contenido, no aparece)
	s = s .. construct_field('author', c)
	s = s .. construct_field('translator', c)
	s = s .. construct_field('editor', c)
	s = s .. construct_field('introducer', c)
	s = s .. construct_field('title', c)
	s = s .. construct_field('subtitle', c)
	s = s .. construct_field('volume', c)
	s = s .. construct_field('year', c)
	s = s .. construct_field('place', c)
	s = s .. construct_field('country', c)
	s = s .. construct_field('printer', c)
	s = s .. construct_field('editorial', c)
	s = s .. construct_field('illustrator', c)
	s = s .. construct_field('editionof', c)
	s = s .. construct_field('source', c)
	s = s .. construct_field('serie', c)
	s = s .. construct_field('modernizar', c)
	s = s .. construct_field('wikidata', c)
	s = s .. construct_field('quality', c)
	s = s .. "<tr><td>[[Archivo:Commons-emblem-notice.svg|20px|enlace=|alt=|frameless]]</td><td> '''[[Ayuda:Índices|Ayuda]]'''</td></tr>"
	s = s .. construct_field_paginas(args['Paginas'], c)
	s = s .. construct_field_sumario(args['Notas'])
	s = s .. '</tr></table>'
	
	if wTitulo:inNamespace(104) then
		s = s .. cats:getCats()
	else
		mw.log(cats:getCats())
	end
	return s
	
end

return p