Module:Wikidata/Nommage/Bac à sable

 Documentation[voir] [modifier] [historique] [purger]

Utilisation

modifier

Fonctions exportables :

  • nameForItem(frame) – interface du modèle permettant de trouver le nommage d’un élément en fonction de la date-valeur d’une propriété d’un autre élément.
  • NameAtPropValue(toNameEntity, AtDateProperty, forItem) – retourne le nom de l’entité à nommer à la date donnée par la valeur de propriété pour l’élément (optionnel, par défaut l’élément associé à la page)
    toNameEntity : identifiant Wikidata d’un élément (ex: «Q1»)
    AtDateProperty: identifiant d’une propriété Wikidata de type de donnée date (ex: «P1448», date de naissance)
  • NameAtDate(toNameEntity, date) – fonction retournant le nom d’une entité à une certaine date, si trouvé, ou nil sinon

Autres fonctions :

  • fonction() – description2 (courte description de fonction() et autres informations pertinentes).

Modules externes et autres éléments dont ce module a besoin pour fonctionner :

  • Module:Wikidata – pour l’extraction des données Wikidata

Exemples

modifier

Évry-Petit-Bourg

-- Module Wikidata d’aide à la gestion du nommage des entités, en particulier le nommage des entités à une date donnée
-- Work In Progress version « marche pas »

local wikidata = require "Module:Wikidata"
local path = require "Module:Wikidata/Chemin"
local modules = {}
modules.formatDate = require "Module:Date complexe"
local fun = require "Module:Luafun"

local PofficialName = "P1448"
local PDateNaissance = "P569"

local p = {}
p.wd = wikidata

-------------------------------------------------------------
-- copied from Module:Wikidata as these are not local functions for now
local function timeFromSnak(snak)
	if snak and snak.snaktype == "value" then
		return snak.datavalue.value.time
	end
end

local function timeFromQualifs(claim, qualifs)
	local claimqualifs = claim.qualifiers
	if not claimqualifs then
		return nil
	end
	for i, qualif in pairs(qualifs or timequalifiers) do
		local vals = claimqualifs[qualif] or {}
		local cand = timeFromSnak(vals[1])
		if cand then return cand end
	end
end

local function atDate(claim, mydate)
	if mydate == "today" or not mydate then
		mydate = os.date("!%Y-%m-%dT%TZ")
	end	
	
	local newclaims = {}
	local mindate = timeFromQualifs(claim, {'P580'}) 
	local maxdate = timeFromQualifs(claim, {'P582'})
	mw.log("my" .. tostring(mydate))
	mw.log("min " .. tostring(mindate))
	mw.log("max" .. tostring(maxdate))
	if modules.formatDate.before(mydate, mindate) and  modules.formatDate.before(maxdate, mydate) then
		return true
	end
end
-------------------------------------------------------------------------------------------

local function stmtMeetsOneTrueIn(condition, values)
	return function(stmt)
		return values:any(
			function(date) return condition(stmt, date) end
		)
	end
end

local function mainSnak(stmt)
	return stmt.mainsnak
end

local function transform_if(cond, transform)
	return function(val)
		if cond(val) then 
			return transform(val)
		else
			return val
		end
	end
end

-- returns a table of possible values « property_id » for statements on « toname_qid » 
-- valid at any of the « date vals » iterator list (values are wikibase date objects)
p.valAtDateVals = function(toname_qid, date_vals_iterator, property_id)
	local vals = mw.wikibase.getAllStatements(toname_qid, property_id)
	local atOneOfTheDates = stmtMeetsOneTrueIn(atDate, date_vals_iterator)
		
	vals = wikidata.filterClaims(
		vals, 
		{
			['condition'] = atOneOfTheDates, 
			['rank'] = 'valid',
			['isinlang'] = 'fr'
		}
	)
	vals = wikidata.sortClaims(vals, "chronological")
	
	-- use the item label in the lang if the official name in the language is still valid now, 
	-- to avoid too windy names when there is more common one
	local subst_with_current_label = function (stmt)
		local currentlabel = mw.wikibase.getLabel(toname_qid)
		if currentlabel then
			stmt.mainsnak.datavalue.value.text = currentlabel
		end
		return stmt
	end
	if not vals then return nil end
	
	-- substitute common names in name statement that are valid at present day statements
	-- and keep multiple values if relevant
	return fun.iter(vals):map(transform_if(atDate, subst_with_current_label)):totable()
end

p.nameAtDate = function (place_qid, date_claims)
	return p.valAtDateVals(place_qid, 
		                   fun.iter(date_claims):map(mainSnak):map(timeFromSnak),
		                   PofficialName
		                   )
end

p.nameAtSnakDate = function (place_qid, date_snaks)
	return p.valAtDateVals(place_qid, 
		                   date_snaks,
		                   PofficialName
		                   )
end


-- =p.nameAtPropValue("Q192393", "P569" ,"Q2977199")
p.nameAtPropValue = function(toNameEntity, atDateProperty, forItem)
	local dates
	if type(forItem) == "table" then
		dates = forItem:getBestStatements(atDateProperty)
	else
	    dates = mw.wikibase.getBestStatements(forItem, atDateProperty)
	end
	local names = p.nameAtDate(toNameEntity, dates)
	return names
end

-- deprecated function, to delete after they have been removed from « Module:Infobox/Fonctions/Personne
local const_format = function(label)
	return function()
		return label
	end
end

-- utility : returns a new version of a dictionary 
--           with the same value except for the keys also present in « delta »,
--           who are set to the values of the corresponding values in delta
-- without modifying the initial dictionary
local function modify_parameters(orig, delta)
	local modified = orig
	for k, v in pairs(delta) do
		modified[k] = v
	end
	return modified
end

-- deprecated function, to delete after they have been removed from « Module:Infobox/Fonctions/Personne
local function alternate_label_statement_formatter(stmt, params, label_get_function, conj)
		local snak = stmt.mainsnak
		if snak.snaktype ~= 'value' then
			return nil
		end
		local labels = label_get_function(snak)
		if labels then
			local label = wikidata.formatStatements{
				claims=labels, conjtype = conj
			}
			return wikidata.formatEntity(wikidata.getId(snak), modify_parameters(params, {labelformat=const_format(label), statementformat=nil}))
		else
			return wikidata.formatEntity(wikidata.getId(snak), modify_parameters(params, {statementformat=nil}))
		end
end

--------------------------------------------------------------------------------------------
-- Formatter generators.
--  These are functions which generates closure able to be used as « statementformat »
--  parameter for the formatting function family of [[Module:Wikidata]] (eg. formatAndCat )
--
--------------------------------------------------------------------------------------------

--[[ generate a formatter for statements, that displays a label according to the date given by another property
     
     (conj is optional)
     
     When called, the return function will use the values for the property 
     « dateOfProperty » of the reference item to search for the names of an item at those time(s)
     
     dateOfProperty : the date datatype property id statements of which gives the reference date
     item : the item on which we will search the reference date
     conj (optional, default « ou ») : if several names are found, 
                                       they all will be displayed separated by the separator
--]]
-- deprecated function, to delete after they have been removed from « Module:Infobox/Fonctions/Personne

--[[test
=p.wd.formatAndCat(
					{
						entity = "Q16615765",  -- monsieur à la scolarité à l’école des chartes alors qu’elle était impériale
						property= 'P69', 
						rank = 'best', 
						conjtype= ' et ', 
						unknownlabel = "lieu inconnu",
						statementformat = p.nameAtStatementDateStatementFormatter(" puis ")
					})
--]]

function it_to_table(path_it)
	local tabl = {}
	for val in path_it do
		mw.logObject(val)
		tabl[#tabl + 1] = val
	end
	return tabl
end

p.nameAtStatementDateStatementFormatter = function(conj)
	conj = conj or " ou "
	return function(stmt, params)
		local dates = it_to_table(path.iterate(stmt, ">(P580|P582|P585)"))
		dates = fun.iter(dates):map(timeFromSnak):totable()
		table.sort(dates)
		
		return alternate_label_statement_formatter(
			stmt, 
			params, 
			function(snak)
				local labels = p.nameAtSnakDate(wikidata.getId(snak), fun.iter(dates))
				return labels
			end,
			conj
		)
	end
end


local linguistic = require "Module:Linguistique"

--[[test 
=p.wd.formatAndCat(
					{
						entity = "Q2977199", 
						property= 'P19', 
						rank = 'best', 
						conjtype= ' ou ', 
						unknownlabel = "lieu inconnu",
						labelformat = p.nameAtDatePropLabelFormatter("P569", "Q2977199")
					})
--]]

p.nameAtDatePropLabelFormatter = function(dateOfProperty, item, params)
	return function(qid)
		local labels = p.nameAtPropValue(qid, "P569", item)
		if labels then
			return linguistic.conj(
				fun.iter(labels):map(
					function (stmt) return wikidata.formatStatement(stmt, params) end
				):totable(),
				"or" --params.conjtype or "or"
			)
		else
			return wikidata.getLabel(qid, params)
		end
	end
end


-- interface for a test template
p.nameForItem = function(frame)
	local item = frame.args["item"]
	local atDateProperty = frame.args["atDateProperty"]
	local toNameEntity = frame.args["toNameEntity"]
	local res = p.nameAtPropValue(toNameEntity, atDateProperty, item)
	if res then
		return wikidata.formatStatements{
			claims=res, conj=" ou "
		}
	else
		return mw.wikibase.label(toNameEntity)
	end
end

return p