use std::collections::BTreeMap;
use graphrt_core::grounding::entities::{AttributionRules, Entities};
use graphrt_core::grounding::figures::NumberRules;
use graphrt_core::template::Template;
use graphrt_core::value::Value;
use graphrt_core::{NodeError, Selector, VariablePool};
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AttributionConfig {
entities: Vec<EntitySource>,
#[serde(default)]
groups: Vec<String>,
#[serde(default)]
scopes: Option<Scopes>,
#[serde(default)]
skip: SkipConfig,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum EntitySource {
Value(Selector),
Labelled(LabelledSource),
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct LabelledSource {
from: Selector,
#[serde(default = "default_label_key")]
label: String,
}
fn default_label_key() -> String {
"entity".to_owned()
}
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum Scopes {
Value(Selector),
Fields(BTreeMap<String, String>),
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SkipConfig {
#[serde(default = "default_integers_up_to")]
integers_up_to: u32,
}
impl Default for SkipConfig {
fn default() -> Self {
Self { integers_up_to: default_integers_up_to() }
}
}
fn default_integers_up_to() -> u32 {
10
}
impl EntitySource {
fn selector(&self) -> &Selector {
match self {
Self::Value(selector) | Self::Labelled(LabelledSource { from: selector, .. }) => selector,
}
}
fn label_key(&self) -> &str {
match self {
Self::Value(_) => "entity",
Self::Labelled(LabelledSource { label, .. }) => label,
}
}
}
pub(super) struct Attribution {
entities: Entities,
scopes: Vec<(String, String)>,
rules: AttributionRules,
}
impl AttributionConfig {
pub(super) fn problem(&self) -> Option<&'static str> {
self.entities
.is_empty()
.then_some("`attribution` needs `entities`: the values that hold the entities and their facts")
}
pub(super) fn selectors(&self) -> Vec<Selector> {
let mut selectors: Vec<Selector> = self.entity_selectors().cloned().collect();
match &self.scopes {
Some(Scopes::Value(selector)) => selectors.push(selector.clone()),
Some(Scopes::Fields(fields)) => {
for label in fields.values() {
selectors.extend(Template::parse(label).selectors().cloned());
}
}
None => {}
}
selectors
}
pub(super) fn entity_selectors(&self) -> impl Iterator<Item = &Selector> {
self.entities.iter().map(EntitySource::selector)
}
pub(super) fn read(&self, pool: &VariablePool, numbers: NumberRules) -> Result<Attribution, NodeError> {
let mut entities = Entities::new();
for source in &self.entities {
let Some(value) = pool.get(source.selector()) else { continue };
entities.add_json(&json_of(&value), source.label_key()).map_err(|problem| {
grounding_error(format!("`attribution.entities` {}: {problem}", source.selector()))
})?;
}
for group in &self.groups {
entities.add_group(group);
}
let scopes = match &self.scopes {
None => Vec::new(),
Some(Scopes::Fields(fields)) => {
fields.iter().map(|(field, label)| (field.clone(), Template::parse(label).render(pool))).collect()
}
Some(Scopes::Value(selector)) => match pool.get(selector).map(|value| json_of(&value)) {
None | Some(serde_json::Value::Null) => Vec::new(),
Some(serde_json::Value::Object(fields)) => fields
.into_iter()
.map(|(field, label)| match label {
serde_json::Value::String(label) => Ok((field, label)),
serde_json::Value::Null => Ok((field, String::new())),
_ => Err(grounding_error(format!(
"`attribution.scopes` {selector}: the scope of `{field}` must be an entity label (a string)"
))),
})
.collect::<Result<_, _>>()?,
Some(_) => {
return Err(grounding_error(format!(
"`attribution.scopes` {selector}: expected an object of field to entity label"
)));
}
},
};
let rules = AttributionRules { numbers, integers_up_to: f64::from(self.skip.integers_up_to) };
Ok(Attribution { entities, scopes, rules })
}
}
impl Attribution {
pub(super) fn findings(&self, field: &str, text: &str, found: &mut Vec<Value>) {
for wrong in self.entities.misattributed(text, self.scope_of(field), self.rules) {
found.push(Value::object([
("field", Value::from(field)),
("number", Value::from(wrong.number)),
("sentence", Value::from(wrong.sentence)),
("reason", Value::from("attribution")),
("named", Value::from(wrong.named)),
("owners", Value::array(wrong.owners.into_iter().map(Value::from))),
]));
}
}
}
impl Attribution {
fn scope_of(&self, field: &str) -> Option<&str> {
let pattern = any_index(field);
let mut best: Option<(usize, &str)> = None;
for (key, label) in &self.scopes {
let covers = |path: &str| {
path == key
|| path
.strip_prefix(key.as_str())
.is_some_and(|rest| rest.starts_with('[') || rest.starts_with('.'))
};
if (covers(field) || covers(&pattern)) && best.is_none_or(|(length, _)| key.len() > length) {
best = Some((key.len(), label));
}
}
best.map(|(_, label)| label)
}
}
fn any_index(field: &str) -> String {
let mut pattern = String::with_capacity(field.len());
let mut rest = field;
while let Some(open) = rest.find('[') {
let (before, after) = rest.split_at(open);
pattern.push_str(before);
match after.find(']') {
Some(close) if after.get(1..close).is_some_and(|index| index.chars().all(|c| c.is_ascii_digit())) => {
pattern.push_str("[*]");
rest = after.get(close + 1..).unwrap_or_default();
}
_ => {
pattern.push('[');
rest = after.get(1..).unwrap_or_default();
}
}
}
pattern.push_str(rest);
pattern
}
fn json_of(value: &Value) -> serde_json::Value {
match value {
Value::String(text) => serde_json::from_str(text).unwrap_or_else(|_| value.to_json()),
other => other.to_json(),
}
}
fn grounding_error(message: String) -> NodeError {
NodeError::fatal("grounding", message)
}