ie-schema 0.1.5

A flexible schema specification and parser for information extraction tasks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::lifted::{LiftedClassification, LiftedJsonStructure, LiftedRelation, LiftedSchema};
use crate::normalized::ExpandedName;
use serde::Serialize;
use std::collections::BTreeMap;
use std::convert::TryFrom;

/// Semantic planning layer between LiftedSchema and prompt/token generation.
///
/// Responsibilities:
/// - compile lifted schema into explicit task units
/// - preserve deterministic ordering
/// - keep task types separate
/// - avoid tokenizer / tensor concerns
///
/// Non-responsibilities:
/// - vocabulary lookup
/// - token IDs
/// - string formatting for final prompts
/// - tensor construction

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum TaskKind {
    Entity,
    Relation,
    Structure,
    Classification,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct EntityTaskPlan {
    /// Entities to extract directly from text.
    pub entities: Vec<ExpandedName>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RelationTaskPlan {
    /// Relation/task name.
    pub relation: ExpandedName,

    /// Head entity reference.
    pub head: ExpandedName,

    /// Tail entity reference.
    pub tail: ExpandedName,

    /// Optional human-readable description carried forward for prompt rendering.
    pub description: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StructureChildPlan {
    /// Property name in the structure.
    pub property: ExpandedName,

    /// Optional choices for closed-set properties.
    pub choices: Vec<ExpandedName>,

    /// Optional description to support later prompt rendering.
    pub description: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StructureTaskPlan {
    /// Structure/task name.
    pub structure: ExpandedName,

    /// Ordered child/property definitions.
    pub children: Vec<StructureChildPlan>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ClassificationTaskPlan {
    /// Classification task entity.
    pub task: ExpandedName,

    /// Allowed label entities.
    pub labels: Vec<ExpandedName>,

    pub threshold: Option<f64>,
    pub multi_label: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub enum PlannedTask {
    Entity(EntityTaskPlan),
    Relation(RelationTaskPlan),
    Structure(StructureTaskPlan),
    Classification(ClassificationTaskPlan),
}

#[derive(Debug, Clone, PartialEq, Serialize, Default)]
pub struct TaskPlan {
    /// Canonical entity registry from LiftedSchema.
    pub entities: BTreeMap<ExpandedName, TaskEntityDef>,

    /// Planned tasks in deterministic execution / rendering order.
    pub tasks: Vec<PlannedTask>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TaskEntityDef {
    pub name: ExpandedName,
    pub description: Option<String>,
    pub threshold: Option<f64>,
    pub dtype: Option<String>,
}

#[derive(Debug, thiserror::Error)]
pub enum TaskPlanError {
    #[error("relation task missing acquired endpoints: {name}")]
    RelationMissingEndpoints { name: String },

    #[error("referenced entity not found in registry: {name}")]
    MissingEntity { name: String },

    #[error("duplicate structure child {child} in structure {structure}")]
    DuplicateStructureChild { structure: String, child: String },
}

fn dtype_to_string(dtype: &super::normalized::DType) -> String {
    match dtype {
        super::normalized::DType::String => "string".to_string(),
        super::normalized::DType::Int => "int".to_string(),
        super::normalized::DType::Float => "float".to_string(),
        super::normalized::DType::Bool => "bool".to_string(),
    }
}

fn build_entity_registry(schema: &LiftedSchema) -> BTreeMap<ExpandedName, TaskEntityDef> {
    schema
        .entities
        .iter()
        .map(|(name, entity)| {
            (
                name.clone(),
                TaskEntityDef {
                    name: name.clone(),
                    description: entity.description.clone(),
                    threshold: entity.threshold,
                    dtype: entity.dtype.as_ref().map(dtype_to_string),
                },
            )
        })
        .collect()
}

fn ensure_entity_exists(
    registry: &BTreeMap<ExpandedName, TaskEntityDef>,
    name: &ExpandedName,
) -> Result<(), TaskPlanError> {
    if registry.contains_key(name) {
        Ok(())
    } else {
        Err(TaskPlanError::MissingEntity {
            name: name.to_string(),
        })
    }
}

fn entity_task_from_schema(
    schema: &LiftedSchema,
    registry: &BTreeMap<ExpandedName, TaskEntityDef>,
) -> Result<Option<PlannedTask>, TaskPlanError> {
    if schema.entities.is_empty() {
        return Ok(None);
    }

    let mut entities: Vec<ExpandedName> = schema.entities.keys().cloned().collect();
    entities.sort();

    for entity in &entities {
        ensure_entity_exists(registry, entity)?;
    }

    Ok(Some(PlannedTask::Entity(EntityTaskPlan { entities })))
}

fn relation_task_from_relation(
    rel: &LiftedRelation,
    registry: &BTreeMap<ExpandedName, TaskEntityDef>,
) -> Result<PlannedTask, TaskPlanError> {
    match rel {
        LiftedRelation::EmptyAcquired { name, description } => {
            Err(TaskPlanError::RelationMissingEndpoints {
                name: format!(
                    "{}{}",
                    name,
                    description
                        .as_ref()
                        .map(|d| format!(" ({d})"))
                        .unwrap_or_default()
                ),
            })
        }
        LiftedRelation::EntityAcquired {
            name,
            description,
            head,
            tail,
        } => {
            ensure_entity_exists(registry, head)?;
            ensure_entity_exists(registry, tail)?;

            Ok(PlannedTask::Relation(RelationTaskPlan {
                relation: name.clone(),
                head: head.clone(),
                tail: tail.clone(),
                description: description.clone(),
            }))
        }
    }
}

fn structure_task_from_structure(
    js: &LiftedJsonStructure,
    registry: &BTreeMap<ExpandedName, TaskEntityDef>,
) -> Result<PlannedTask, TaskPlanError> {
    let mut children = Vec::with_capacity(js.props.len());

    for (property, prop) in &js.props {
        for choice in &prop.choices {
            ensure_entity_exists(registry, choice)?;
        }

        children.push(StructureChildPlan {
            property: property.clone(),
            choices: prop.choices.clone(),
            description: prop.description.clone(),
        });
    }

    Ok(PlannedTask::Structure(StructureTaskPlan {
        structure: js.name.clone(),
        children,
    }))
}

fn classification_task_from_classification(
    cls: &LiftedClassification,
    registry: &BTreeMap<ExpandedName, TaskEntityDef>,
) -> Result<PlannedTask, TaskPlanError> {
    ensure_entity_exists(registry, &cls.task)?;
    for label in &cls.labels {
        ensure_entity_exists(registry, label)?;
    }

    Ok(PlannedTask::Classification(ClassificationTaskPlan {
        task: cls.task.clone(),
        labels: cls.labels.clone(),
        threshold: cls.threshold,
        multi_label: cls.multi_label,
    }))
}

impl TryFrom<LiftedSchema> for TaskPlan {
    type Error = TaskPlanError;

    fn try_from(schema: LiftedSchema) -> Result<Self, Self::Error> {
        let registry = build_entity_registry(&schema);

        let mut tasks = Vec::new();

        if let Some(entity_task) = entity_task_from_schema(&schema, &registry)? {
            tasks.push(entity_task);
        }

        for rel in &schema.relations {
            tasks.push(relation_task_from_relation(rel, &registry)?);
        }

        for js in &schema.json_structures {
            tasks.push(structure_task_from_structure(js, &registry)?);
        }

        for cls in &schema.classifications {
            tasks.push(classification_task_from_classification(cls, &registry)?);
        }

        Ok(TaskPlan {
            entities: registry,
            tasks,
        })
    }
}

impl TaskPlan {
    pub fn entity_tasks(&self) -> impl Iterator<Item = &EntityTaskPlan> {
        self.tasks.iter().filter_map(|t| match t {
            PlannedTask::Entity(x) => Some(x),
            _ => None,
        })
    }

    pub fn relation_tasks(&self) -> impl Iterator<Item = &RelationTaskPlan> {
        self.tasks.iter().filter_map(|t| match t {
            PlannedTask::Relation(x) => Some(x),
            _ => None,
        })
    }

    pub fn structure_tasks(&self) -> impl Iterator<Item = &StructureTaskPlan> {
        self.tasks.iter().filter_map(|t| match t {
            PlannedTask::Structure(x) => Some(x),
            _ => None,
        })
    }

    pub fn classification_tasks(&self) -> impl Iterator<Item = &ClassificationTaskPlan> {
        self.tasks.iter().filter_map(|t| match t {
            PlannedTask::Classification(x) => Some(x),
            _ => None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::expanded::ExpandedSchema;
    use crate::lifted::LiftedSchema;
    use crate::normalized::NormalizedSchema;

    #[test]
    fn task_plan_builds_entity_relation_structure_and_classification_tasks() {
        let s = r#"
        {
            "entities": [
                "gene::str::0.9::gene symbol",
                "disease::str::0.8::disease entity",
                "patient",
                "record",
                "positive",
                "negative",
                "sentiment"
            ],
            "relations": [
                { "associated_with": { "head": "gene", "tail": "disease" } }
            ],
            "json_structures": [
                {
                    "name": "Patient Record",
                    "status": {
                        "choices": ["positive", "negative"]
                    }
                }
            ],
            "classifications": [
                {
                    "task": "sentiment",
                    "labels": ["positive", "negative"],
                    "multi_label": false
                }
            ]
        }
        "#;

        let s2 = NormalizedSchema::from_json_str(s).unwrap();
        let s3 = ExpandedSchema::try_from(s2).unwrap();
        let s4 = LiftedSchema::try_from(s3).unwrap();
        let plan = TaskPlan::try_from(s4).unwrap();

        assert_eq!(plan.entity_tasks().count(), 1);
        assert_eq!(plan.relation_tasks().count(), 1);
        assert_eq!(plan.structure_tasks().count(), 1);
        assert_eq!(plan.classification_tasks().count(), 1);
    }

    #[test]
    fn task_plan_relation_requires_registered_entities() {
        let s4 = LiftedSchema {
            entities: BTreeMap::new(),
            json_structures: vec![],
            relations: vec![LiftedRelation::EntityAcquired {
                name: ExpandedName::new("associated_with".to_string()),
                description: None,
                head: ExpandedName::new("gene".to_string()),
                tail: ExpandedName::new("disease".to_string()),
            }],
            classifications: vec![],
        };

        let err = TaskPlan::try_from(s4).unwrap_err();
        match err {
            TaskPlanError::MissingEntity { name } => assert_eq!(name, "gene"),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn task_plan_classification_uses_entity_refs() {
        let s = r#"
        {
            "entities": ["sentiment", "positive", "negative"],
            "classifications": [
                {
                    "task": "sentiment",
                    "labels": ["positive", "negative"],
                    "multi_label": true,
                    "threshold": 0.6
                }
            ]
        }
        "#;

        let s2 = NormalizedSchema::from_json_str(s).unwrap();
        let s3 = ExpandedSchema::try_from(s2).unwrap();
        let s4 = LiftedSchema::try_from(s3).unwrap();
        let plan = TaskPlan::try_from(s4).unwrap();

        let cls = plan.classification_tasks().next().unwrap();
        assert_eq!(cls.task.as_str(), "sentiment");
        assert_eq!(cls.labels.len(), 2);
        assert_eq!(cls.labels[0].as_str(), "positive");
        assert_eq!(cls.labels[1].as_str(), "negative");
        assert_eq!(cls.threshold, Some(0.6));
        assert!(cls.multi_label);
    }
}