rudaoshi commited on
Commit
2d45476
·
1 Parent(s): 6dd951d

implement app

Browse files
README.md CHANGED
@@ -1,13 +1,52 @@
1
  ---
2
- title: Lang2logic
3
- emoji: 🖼
4
- colorFrom: purple
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 5.44.0
8
  app_file: app.py
9
  pinned: false
10
- license: gpl
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Word-Lingua Graph Parser
3
+ emoji: 📊
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 4.0.0
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
  ---
12
 
13
+ # Word-Lingua Graph Parser
14
+
15
+ Parse sentences into linguistic structure graphs using deep learning.
16
+
17
+ ## Model
18
+
19
+ This Space uses the [rudaoshi/lingua](https://huggingface.co/rudaoshi/lingua) model, which is a BERT-based parser with biaffine attention for word-lingua graph prediction.
20
+
21
+ ## Features
22
+
23
+ - **Sentence Parsing**: Input any English sentence to parse it into a linguistic structure graph
24
+ - **Graph Visualization**: Visualize the parsed graph with nodes and edges
25
+ - **Constrained Decoding**: Use pattern-based constrained decoding for better graph structure (enabled by default)
26
+
27
+ ## Usage
28
+
29
+ 1. Enter a sentence in the text box
30
+ 2. Optionally toggle "Use Constrained Decoding" (recommended)
31
+ 3. Click "Parse Sentence" to generate the graph visualization
32
+
33
+ ## Example Sentences
34
+
35
+ - "The cat sat on the mat."
36
+ - "John loves Mary."
37
+ - "I want to go to the store."
38
+
39
+ ## Graph Structure
40
+
41
+ The parser generates word-lingua graphs that represent:
42
+ - Predicate-argument relations (pred.arg.1, pred.arg.2, etc.)
43
+ - Modification relations (@modification, etc.)
44
+ - Discourse markers
45
+ - And more linguistic structures
46
+
47
+ ## Technical Details
48
+
49
+ - **Model Architecture**: BERT + Biaffine Attention
50
+ - **Decoding**: Greedy pattern-based constrained decoding
51
+ - **Output Format**: GPGraph (linguistic graph structure)
52
+
app.py CHANGED
@@ -1,154 +1,550 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
- import torch
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
  """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
 
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
 
 
 
 
 
 
 
 
 
 
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
 
 
 
 
 
81
 
82
- result = gr.Image(label="Result", show_label=False)
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
 
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
 
 
 
 
 
 
 
 
 
 
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
 
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  ],
150
- outputs=[result, seed],
151
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  if __name__ == "__main__":
154
  demo.launch()
 
 
 
 
 
 
1
+ """
2
+ Gradio app for Word-Lingua Graph Parser
 
3
 
4
+ This app loads the model from HuggingFace Hub and provides an interactive interface
5
+ to parse sentences and visualize the resulting graph.
 
6
 
7
+ Designed for HuggingFace Space deployment.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  """
9
 
10
+ import os
11
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
 
12
 
13
+ import sys
14
+ import json
15
+ import torch
16
+ import numpy as np
17
+ import tempfile
18
+ from typing import Dict, List, Tuple, Optional
19
+ from collections import Counter, defaultdict
20
+
21
+ from transformers import AutoTokenizer
22
+ from huggingface_hub import hf_hub_download
23
+
24
+ # Add lingua_space directory to path (lingua is now a package)
25
+ sys.path.insert(0, os.path.dirname(__file__))
26
+
27
+ # Import model and graph classes
28
+ from model import WordLinguaParserV2, ID2NODE_TYPE
29
+ from lingua.structure.gpgraph import GPGraph, GPGPhraseNode, GPGEdge, GPGraphVisualizer
30
+ from lingua.learn.wordgraph.modeler.word2gp import wordlingua2lingua
31
 
32
+ # Import constrained decoding classes from inference.py
33
+ # For HuggingFace Space, inference.py should be in the same directory
34
+ from inference import EdgePatternStats, GreedyPatternDecoder
35
+
36
+ import gradio as gr
37
+
38
+ # Model ID for HuggingFace Hub
39
+ MODEL_ID = "rudaoshi/lingua"
40
 
 
41
 
42
+ # ============================================================================
43
+ # Model Loading
44
+ # ============================================================================
45
+
46
+ class ModelLoader:
47
+ """Singleton class to load and cache the model."""
48
+
49
+ _instance = None
50
+ _model = None
51
+ _tokenizer = None
52
+ _label2id = None
53
+ _id2label = None
54
+ _device = None
55
+ _constrained_decoder = None
56
+ _stats = None
57
+
58
+ def __new__(cls):
59
+ if cls._instance is None:
60
+ cls._instance = super().__new__(cls)
61
+ return cls._instance
62
+
63
+ def load_model(self, model_name_or_path: str,
64
+ arc_hidden_size: int = 512,
65
+ rel_hidden_size: int = 256,
66
+ node_hidden_size: int = 256,
67
+ word_pooling: str = "mean"):
68
+ """Load the model from HuggingFace directory or Hub."""
69
+ if self._model is not None:
70
+ return # Already loaded
71
+
72
+ print(f"Loading model from {model_name_or_path}...")
73
+
74
+ # Set up device
75
+ self._device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
76
+ print(f"Using device: {self._device}")
77
+
78
+ # Check if it's a HuggingFace Hub model ID (contains '/' and not a local path)
79
+ is_hub_model = '/' in model_name_or_path and not os.path.exists(model_name_or_path)
80
+
81
+ # Load label2id
82
+ if is_hub_model:
83
+ print("Downloading label2id.json from HuggingFace Hub...")
84
+ label2id_path = hf_hub_download(
85
+ repo_id=model_name_or_path,
86
+ filename="label2id.json"
87
+ )
88
+ else:
89
+ label2id_path = os.path.join(model_name_or_path, "label2id.json")
90
+ if not os.path.exists(label2id_path):
91
+ raise FileNotFoundError(f"label2id.json not found in {model_name_or_path}")
92
+
93
+ with open(label2id_path, 'r') as f:
94
+ self._label2id = json.load(f)
95
+ self._id2label = {v: k for k, v in self._label2id.items()}
96
+
97
+ # Load tokenizer
98
+ print("Loading tokenizer...")
99
+ self._tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
100
+
101
+ # Create model
102
+ print("Creating model...")
103
+ self._model = WordLinguaParserV2(
104
+ bert_model_name=model_name_or_path,
105
+ label_num=len(self._label2id),
106
+ arc_hidden_size=arc_hidden_size,
107
+ rel_hidden_size=rel_hidden_size,
108
+ node_hidden_size=node_hidden_size,
109
+ dropout=0.0,
110
+ word_pooling=word_pooling
111
+ )
112
+
113
+ # Load model weights
114
+ if is_hub_model:
115
+ print("Downloading pytorch_model.bin from HuggingFace Hub...")
116
+ model_path = hf_hub_download(
117
+ repo_id=model_name_or_path,
118
+ filename="pytorch_model.bin"
119
  )
120
+ else:
121
+ model_path = os.path.join(model_name_or_path, "pytorch_model.bin")
122
+ if not os.path.exists(model_path):
123
+ raise FileNotFoundError(f"pytorch_model.bin not found in {model_name_or_path}")
124
+
125
+ print("Loading model weights...")
126
+ state_dict = torch.load(model_path, map_location=self._device)
127
+ if isinstance(state_dict, dict) and 'model_state_dict' in state_dict:
128
+ self._model.load_state_dict(state_dict['model_state_dict'])
129
+ else:
130
+ self._model.load_state_dict(state_dict)
131
+
132
+ self._model.to(self._device)
133
+ self._model.eval()
134
+ print("Model loaded successfully!")
135
+
136
+ # Load constrained decoding statistics if available
137
+ self._load_constrained_decoding_stats(model_name_or_path, is_hub_model)
138
+
139
+ def _load_constrained_decoding_stats(self, model_name_or_path: str, is_hub_model: bool):
140
+ """Load edge pattern statistics for constrained decoding."""
141
+ try:
142
+ if is_hub_model:
143
+ print("Downloading edge_pattern_stats.json from HuggingFace Hub...")
144
+ stats_path = hf_hub_download(
145
+ repo_id=model_name_or_path,
146
+ filename="edge_pattern_stats.json"
147
+ )
148
+ else:
149
+ stats_path = os.path.join(model_name_or_path, "edge_pattern_stats.json")
150
+ if not os.path.exists(stats_path):
151
+ print("edge_pattern_stats.json not found, constrained decoding will be disabled.")
152
+ return
153
+
154
+ print("Loading edge pattern statistics...")
155
+ self._stats = EdgePatternStats()
156
+ self._stats.load(stats_path)
157
+
158
+ # Create constrained decoder
159
+ self._constrained_decoder = GreedyPatternDecoder(
160
+ stats=self._stats,
161
+ id2label=self._id2label,
162
+ label2id=self._label2id,
163
+ arc_threshold=0.5
164
+ )
165
+ print("Constrained decoding ready!")
166
+ except Exception as e:
167
+ print(f"Warning: Could not load constrained decoding stats: {e}")
168
+ print("Constrained decoding will be disabled.")
169
+
170
+ @property
171
+ def constrained_decoder(self):
172
+ return self._constrained_decoder
173
+
174
+ @property
175
+ def model(self):
176
+ return self._model
177
+
178
+ @property
179
+ def tokenizer(self):
180
+ return self._tokenizer
181
+
182
+ @property
183
+ def id2label(self):
184
+ return self._id2label
185
+
186
+ @property
187
+ def device(self):
188
+ return self._device
189
+
190
+
191
+ # ============================================================================
192
+ # Graph Reconstruction
193
+ # ============================================================================
194
+
195
+ def predictions_to_word_lingua_graph(
196
+ words: List[str],
197
+ arc_preds: np.ndarray, # [num_words, num_words] binary
198
+ rel_preds: np.ndarray, # [num_words, num_words] label ids
199
+ node_type_preds: np.ndarray, # [num_words] node type ids
200
+ is_root_preds: np.ndarray, # [num_words] binary
201
+ child_of_whether_preds: np.ndarray, # [num_words] binary
202
+ id2label: Dict[int, str],
203
+ ) -> GPGraph:
204
+ """Reconstruct a word-lingua-graph from model predictions."""
205
+ # Create a new GPGraph
206
+ graph = GPGraph()
207
+ graph.words = words
208
+ graph.sentence = " ".join(words) # Set sentence for visualization
209
+
210
+ num_words = len(words)
211
+
212
+ # Create nodes for each word
213
+ word_to_node = {}
214
+ for i, word in enumerate(words):
215
+ node = GPGPhraseNode(
216
+ ID=str(i),
217
+ spans=[(i, i)],
218
+ pos=ID2NODE_TYPE.get(node_type_preds[i], "NominalConstant")
219
+ )
220
+ # Set child_of_whether attribute if predicted
221
+ if child_of_whether_preds[i]:
222
+ node.child_of_whether = True
223
+
224
+ graph.add_node(node)
225
+ word_to_node[i] = node
226
+
227
+ # Add edges based on arc predictions
228
+ for i in range(num_words):
229
+ for j in range(num_words):
230
+ if arc_preds[i, j]:
231
+ parent_node = word_to_node[i]
232
+ child_node = word_to_node[j]
233
+ label = id2label.get(rel_preds[i, j], "UNK")
234
+
235
+ edge = GPGEdge(label=label)
236
+ graph.add_edge(parent_node, child_node, edge)
237
+
238
+ return graph
239
+
240
 
241
+ # ============================================================================
242
+ # Inference Function
243
+ # ============================================================================
244
+
245
+ def prepare_input(sentence: str, tokenizer, max_length: int = 512) -> Dict:
246
+ """Prepare input for the model from a sentence."""
247
+ # Tokenize
248
+ encoding = tokenizer(
249
+ sentence,
250
+ max_length=max_length,
251
+ truncation=True,
252
+ return_offsets_mapping=True,
253
+ add_special_tokens=True,
254
+ )
255
+
256
+ # Get word boundaries from the sentence
257
+ words = []
258
+ word_starts = []
259
+ current_pos = 0
260
+ for i, char in enumerate(sentence):
261
+ if char == ' ':
262
+ if current_pos < i:
263
+ words.append(sentence[current_pos:i])
264
+ word_starts.append(current_pos)
265
+ current_pos = i + 1
266
+ if current_pos < len(sentence):
267
+ words.append(sentence[current_pos:])
268
+ word_starts.append(current_pos)
269
+
270
+ # Map words to subword indices
271
+ offset_mapping = encoding.get("offset_mapping", [])
272
+ word_to_subword = []
273
+
274
+ for word_idx, word_start in enumerate(word_starts):
275
+ word_end = word_start + len(words[word_idx])
276
+ subword_indices = []
277
+
278
+ for subword_idx, (start, end) in enumerate(offset_mapping):
279
+ if start == end: # Skip special tokens
280
+ continue
281
+ # Check if subword overlaps with word
282
+ if start < word_end and end > word_start:
283
+ subword_indices.append(subword_idx)
284
+
285
+ if not subword_indices:
286
+ # Fallback: assign to nearest subword
287
+ for subword_idx, (start, end) in enumerate(offset_mapping):
288
+ if start == end:
289
+ continue
290
+ if start >= word_start:
291
+ subword_indices = [subword_idx]
292
+ break
293
+
294
+ word_to_subword.append(subword_indices if subword_indices else [0])
295
+
296
+ return {
297
+ "input_ids": encoding["input_ids"],
298
+ "attention_mask": encoding["attention_mask"],
299
+ "word_to_subword": word_to_subword,
300
+ "num_words": len(words),
301
+ "words": words,
302
+ }
303
+
304
+
305
+ def parse_sentence(sentence: str, model_loader: ModelLoader, use_constrained: bool = True) -> Tuple[GPGraph, str]:
306
+ """Parse a sentence and return the graph."""
307
+ if not sentence.strip():
308
+ return None, "Please enter a sentence."
309
+
310
+ try:
311
+ # Prepare input
312
+ tokenizer = model_loader.tokenizer
313
+ input_data = prepare_input(sentence, tokenizer)
314
+
315
+ # Convert to tensors
316
+ input_ids = torch.tensor([input_data["input_ids"]], dtype=torch.long).to(model_loader.device)
317
+ attention_mask = torch.tensor([input_data["attention_mask"]], dtype=torch.bool).to(model_loader.device)
318
+
319
+ max_words = input_data["num_words"]
320
+ max_subwords = max(len(subwords) for subwords in input_data["word_to_subword"])
321
+
322
+ word_to_subword = torch.full((1, max_words, max_subwords), -1, dtype=torch.long).to(model_loader.device)
323
+ word_mask = torch.ones(1, max_words, dtype=torch.bool).to(model_loader.device)
324
+
325
+ for w_idx, subword_indices in enumerate(input_data["word_to_subword"]):
326
+ for s_idx, subword_idx in enumerate(subword_indices):
327
+ word_to_subword[0, w_idx, s_idx] = subword_idx
328
+
329
+ # Run inference
330
+ with torch.no_grad():
331
+ outputs = model_loader.model(
332
+ input_ids=input_ids,
333
+ attention_mask=attention_mask,
334
+ word_to_subword=word_to_subword,
335
+ word_mask=word_mask
336
+ )
337
+
338
+ # Get predictions
339
+ arc_logits = outputs["arc_logits"][0].cpu().numpy() # [num_words, num_words]
340
+ rel_logits = outputs["rel_logits"][0].cpu().numpy() # [num_words, num_words, num_labels]
341
+ child_of_whether_logits = outputs["child_of_whether_logits"][0].cpu().numpy() # [num_words, 2]
342
+ is_root_logits = outputs["is_root_logits"][0].cpu().numpy() # [num_words, 2]
343
+ node_type_logits = outputs["node_type_logits"][0].cpu().numpy() # [num_words, num_types]
344
+
345
+ # Decode predictions
346
+ num_words = len(input_data["words"])
347
+
348
+ # Node predictions
349
+ child_of_whether_preds = np.argmax(child_of_whether_logits, axis=-1) # [num_words]
350
+ node_type_preds = np.argmax(node_type_logits, axis=-1) # [num_words]
351
+
352
+ # Use constrained decoding if available and requested
353
+ if use_constrained and model_loader.constrained_decoder is not None:
354
+ word_lingua_graph, decoding_info = model_loader.constrained_decoder.decode(
355
+ words=input_data["words"],
356
+ arc_logits=arc_logits,
357
+ rel_logits=rel_logits,
358
+ node_type_preds=node_type_preds,
359
+ is_root_logits=is_root_logits,
360
+ child_of_whether_preds=child_of_whether_preds,
361
+ )
362
+ graph = word_lingua_graph
363
+ else:
364
+ # Simple thresholding decoding
365
+ arc_preds = (arc_logits > 0).astype(int)
366
+ rel_preds = np.argmax(rel_logits, axis=-1) # [num_words, num_words]
367
+
368
+ # Ensure there's exactly one root node
369
+ root_probs = torch.softmax(torch.tensor(is_root_logits), dim=-1)[:, 1].numpy()
370
+ root_idx = int(np.argmax(root_probs))
371
+ is_root_preds = np.zeros(num_words, dtype=int)
372
+ is_root_preds[root_idx] = 1
373
+
374
+ # Reconstruct word-lingua-graph
375
+ word_lingua_graph = predictions_to_word_lingua_graph(
376
+ words=input_data["words"],
377
+ arc_preds=arc_preds,
378
+ rel_preds=rel_preds,
379
+ node_type_preds=node_type_preds,
380
+ is_root_preds=is_root_preds,
381
+ child_of_whether_preds=child_of_whether_preds,
382
+ id2label=model_loader.id2label
383
  )
384
+ graph = word_lingua_graph
385
+
386
+ # Convert word-lingua-graph to linguagraph
387
+ try:
388
+ linguagraph, _ = wordlingua2lingua(graph)
389
+ graph = linguagraph
390
+ except Exception as e:
391
+ # If conversion fails, return the word-lingua-graph with a warning
392
+ return graph, f"Warning: Failed to convert to linguagraph: {str(e)}. Returning word-lingua-graph."
393
+
394
+ return graph, None
395
+
396
+ except Exception as e:
397
+ import traceback
398
+ error_msg = f"Error parsing sentence: {str(e)}\n{traceback.format_exc()}"
399
+ return None, error_msg
400
 
 
401
 
402
+ def visualize_graph(graph: GPGraph) -> Optional[str]:
403
+ """Visualize graph and return path to temporary image file."""
404
+ if graph is None:
405
+ return None
406
+
407
+ try:
408
+ # Create temporary file
409
+ temp_fd, temp_file = tempfile.mkstemp(suffix=".png")
410
+ os.close(temp_fd)
411
+
412
+ # Visualize
413
+ visualizer = GPGraphVisualizer()
414
+ visualizer.visualize(graph, file_name=temp_file, format="png")
415
+
416
+ return temp_file
417
+ except Exception as e:
418
+ print(f"Error visualizing graph: {e}")
419
+ return None
420
 
 
 
 
 
 
 
 
421
 
422
+ # ============================================================================
423
+ # Gradio Interface
424
+ # ============================================================================
425
+
426
+ def process_sentence(sentence: str) -> Tuple[Optional[str], str]:
427
+ """Process a sentence and return the visualization."""
428
+ try:
429
+ # Load model if not already loaded
430
+ model_loader = ModelLoader()
431
+ if model_loader.model is None:
432
+ model_loader.load_model(MODEL_ID)
433
+
434
+ # Parse sentence (always use constrained decoding if available)
435
+ use_constrained = True
436
+ graph, error = parse_sentence(sentence, model_loader, use_constrained=use_constrained)
437
+
438
+ if error:
439
+ return None, error
440
+
441
+ # Visualize
442
+ img_path = visualize_graph(graph)
443
+
444
+ decoding_mode = "constrained" if (use_constrained and model_loader.constrained_decoder) else "simple"
445
+ if img_path:
446
+ return img_path, f"Graph generated successfully! (Decoding: {decoding_mode})"
447
+ else:
448
+ return None, "Failed to generate visualization."
449
+
450
+ except Exception as e:
451
+ import traceback
452
+ error_msg = f"Error: {str(e)}\n{traceback.format_exc()}"
453
+ return None, error_msg
454
 
 
 
 
 
 
 
 
455
 
456
+ def load_model_on_startup():
457
+ """Load model when the Space starts up."""
458
+ try:
459
+ model_loader = ModelLoader()
460
+ if model_loader.model is None:
461
+ print(f"Loading model {MODEL_ID}...")
462
+ model_loader.load_model(MODEL_ID)
463
+ print("Model loaded successfully!")
464
+ return "Model loaded successfully!"
465
+ return "Model already loaded."
466
+ except Exception as e:
467
+ error_msg = f"Error loading model: {str(e)}"
468
+ print(error_msg)
469
+ return error_msg
470
+
471
+
472
+ # Create Gradio interface
473
+ with gr.Blocks(title="Lingua Graph Parser") as demo:
474
+ gr.Markdown("""
475
+ # Lingua Graph Parser
476
+
477
+ Parse sentences into linguistic structure graphs using deep learning.
478
+
479
+ Enter a sentence below to visualize its linguistic structure as a graph.
480
+ """)
481
+
482
+ with gr.Column():
483
+ with gr.Row():
484
+ sentence_input = gr.Textbox(
485
+ label="Input Sentence",
486
+ placeholder="Enter a sentence here...",
487
+ lines=3,
488
+ info="Type any English sentence to parse",
489
+ scale=4
490
+ )
491
+ parse_btn = gr.Button("Parse Sentence", variant="primary", size="lg", scale=1)
492
+
493
+ output_text = gr.Textbox(
494
+ label="Status",
495
+ lines=3,
496
+ interactive=False
497
+ )
498
+ output_image = gr.Image(
499
+ label="Graph Visualization",
500
+ type="filepath",
501
+ height=600
502
+ )
503
+
504
+ # Load model on startup
505
+ demo.load(
506
+ fn=load_model_on_startup,
507
+ outputs=output_text
508
+ )
509
+
510
+ # Parse button click handler
511
+ parse_btn.click(
512
+ fn=process_sentence,
513
+ inputs=[sentence_input],
514
+ outputs=[output_image, output_text]
515
+ )
516
+
517
+ # Example sentences
518
+ gr.Markdown("### Example Sentences")
519
+ gr.Examples(
520
+ examples=[
521
+ "The cat sat on the mat .",
522
+ "John loves Mary .",
523
+ "I want to go to the store .",
524
+ "The quick brown fox jumps over the lazy dog .",
525
+ "She gave him a book yesterday .",
526
  ],
527
+ inputs=sentence_input
528
  )
529
+
530
+ gr.Markdown("""
531
+ ### About
532
+
533
+ This parser uses a BERT-based model with biaffine attention to parse sentences into
534
+ word-lingua graphs, which represent linguistic structures including:
535
+ - Predicate-argument relations
536
+ - Modification relations
537
+ - Discourse markers
538
+ - And more...
539
+
540
+ **Model**: [rudaoshi/lingua](https://huggingface.co/rudaoshi/lingua)
541
+ """)
542
+
543
 
544
  if __name__ == "__main__":
545
  demo.launch()
546
+
547
+
548
+ # For HuggingFace Space, the demo is already created above
549
+ # No need for main() function
550
+
inference.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Constrained decoding classes for Word-Lingua Graph Parser
3
+
4
+ This module contains only the classes needed for constrained decoding in the Space:
5
+ - EdgePatternStats: Statistics for edge patterns
6
+ - GreedyPatternDecoder: Greedy decoder with pattern constraints
7
+ """
8
+
9
+ import os
10
+ import json
11
+ import logging
12
+ from collections import Counter, defaultdict
13
+ from typing import List, Dict, Tuple, Optional, Any
14
+
15
+ import numpy as np
16
+
17
+ # Import from model.py
18
+ from model import ID2NODE_TYPE
19
+
20
+ # Add lingua_space directory to path (lingua is now a package)
21
+ import sys
22
+ sys.path.insert(0, os.path.dirname(__file__))
23
+
24
+ # Import graph classes
25
+ from lingua.structure.gpgraph import GPGraph, GPGPhraseNode, GPGEdge
26
+
27
+ # Initialize logger if not already initialized
28
+ if not logging.getLogger().handlers:
29
+ logging.basicConfig(
30
+ level=logging.INFO,
31
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
32
+ )
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ # ============================================================================
37
+ # Edge Pattern Statistics
38
+ # ============================================================================
39
+
40
+ class EdgePatternStats:
41
+ """
42
+ Loads and uses edge PATTERN statistics for constrained decoding.
43
+
44
+ Statistics are loaded from edge_pattern_stats.json file which contains:
45
+ - P(outgoing_edge_pattern | incoming_edge, node_type)
46
+ - P(outgoing_edge_pattern | node_type) - fallback
47
+ - Root node type distribution
48
+
49
+ This captures structural constraints like:
50
+ - ModificationalFunctor must have exactly one "variable" and one "body" edge
51
+ - FactualPredicator typically has pred.arg.1, pred.arg.2, etc.
52
+
53
+ An edge pattern is a sorted tuple of outgoing edge labels.
54
+ """
55
+
56
+ def __init__(self):
57
+ # P(outgoing_edge_pattern | incoming_edge, node_type)
58
+ # Key: (incoming_edge, node_type)
59
+ # Value: Counter of edge patterns (sorted tuple of edge labels)
60
+ self.edge_pattern_counts = defaultdict(Counter)
61
+
62
+ # P(outgoing_edge_pattern | node_type) - fallback
63
+ self.node_type_pattern_counts = defaultdict(Counter)
64
+
65
+ # Root node type distribution
66
+ self.root_node_type_counts = Counter()
67
+
68
+ # For debugging: track pattern frequencies
69
+ self.all_patterns = Counter()
70
+
71
+ self.is_fitted = False
72
+
73
+
74
+ def get_valid_patterns(self, incoming_edge: str, node_type: str) -> List[Tuple[Tuple[str, ...], float]]:
75
+ """
76
+ Get valid outgoing edge patterns with their probabilities.
77
+
78
+ Returns:
79
+ List of (pattern, probability) tuples, sorted by probability descending
80
+ """
81
+ key = (incoming_edge, node_type)
82
+
83
+ if key in self.edge_pattern_counts and self.edge_pattern_counts[key]:
84
+ counts = self.edge_pattern_counts[key]
85
+ total = sum(counts.values())
86
+ result = [(pattern, count / total) for pattern, count in counts.items()]
87
+ return sorted(result, key=lambda x: -x[1])
88
+
89
+ # Fallback: use node_type's general pattern distribution
90
+ if node_type in self.node_type_pattern_counts and self.node_type_pattern_counts[node_type]:
91
+ counts = self.node_type_pattern_counts[node_type]
92
+ total = sum(counts.values())
93
+ result = [(pattern, count / total) for pattern, count in counts.items()]
94
+ return sorted(result, key=lambda x: -x[1])
95
+
96
+ # Last fallback: empty pattern (leaf node)
97
+ return [((), 1.0)]
98
+
99
+ def get_pattern_probability(self, incoming_edge: str, node_type: str,
100
+ pattern: Tuple[str, ...]) -> float:
101
+ """Get probability of a specific pattern."""
102
+ key = (incoming_edge, node_type)
103
+
104
+ if key in self.edge_pattern_counts:
105
+ counts = self.edge_pattern_counts[key]
106
+ total = sum(counts.values())
107
+ if total > 0:
108
+ return counts.get(pattern, 0) / total
109
+
110
+ # Fallback
111
+ if node_type in self.node_type_pattern_counts:
112
+ counts = self.node_type_pattern_counts[node_type]
113
+ total = sum(counts.values())
114
+ if total > 0:
115
+ return counts.get(pattern, 0) / total
116
+
117
+ return 0.0
118
+
119
+ def load(self, path: str):
120
+ """Load statistics from file."""
121
+ with open(path, "r") as f:
122
+ data = json.load(f)
123
+
124
+ self.edge_pattern_counts = defaultdict(Counter)
125
+ for k, v in data["edge_pattern_counts"].items():
126
+ key = eval(k) # Convert string back to tuple
127
+ self.edge_pattern_counts[key] = Counter({eval(p): c for p, c in v.items()})
128
+
129
+ self.node_type_pattern_counts = defaultdict(Counter)
130
+ for k, v in data["node_type_pattern_counts"].items():
131
+ self.node_type_pattern_counts[k] = Counter({eval(p): c for p, c in v.items()})
132
+
133
+ self.root_node_type_counts = Counter(data["root_node_type_counts"])
134
+ self.all_patterns = Counter({eval(k): v for k, v in data["all_patterns"].items()})
135
+
136
+ self.is_fitted = True
137
+ logger.info(f"Loaded edge pattern statistics from {path}")
138
+
139
+
140
+ # ============================================================================
141
+ # Greedy Pattern Decoder
142
+ # ============================================================================
143
+
144
+ class GreedyPatternDecoder:
145
+ """
146
+ Bottom-up greedy decoder that constructs the graph edge-by-edge.
147
+
148
+ Strategy:
149
+ 1. Select edges with p(edge) > threshold
150
+ 2. For each candidate edge, compute score = p(edge) * p(label) * p(pattern)
151
+ 3. Greedily select highest-scoring edge that doesn't violate pattern constraints
152
+ 4. After selecting an edge, update pattern constraints for affected nodes
153
+ 5. Connect disconnected components to the root component
154
+
155
+ This avoids cascading errors from top-down approaches.
156
+ """
157
+
158
+ def __init__(self, stats: EdgePatternStats, id2label: Dict[int, str],
159
+ label2id: Dict[str, int], arc_threshold: float = 0.5):
160
+ self.stats = stats
161
+ self.id2label = id2label
162
+ self.label2id = label2id
163
+ self.arc_threshold = arc_threshold
164
+
165
+ def decode(
166
+ self,
167
+ words: List[str],
168
+ arc_logits: np.ndarray,
169
+ rel_logits: np.ndarray,
170
+ node_type_preds: np.ndarray,
171
+ is_root_logits: np.ndarray,
172
+ child_of_whether_preds: np.ndarray,
173
+ ) -> Tuple[GPGraph, Dict[str, Any]]:
174
+ """
175
+ Decode predictions using bottom-up greedy search with pattern constraints.
176
+
177
+ Returns:
178
+ Tuple of (graph, decoding_info) where decoding_info contains:
179
+ - errors: list of error messages
180
+ - warnings: list of warning messages
181
+ - forced_connections: list of forced edge connections
182
+ - disconnected_nodes: list of nodes that couldn't be connected
183
+ """
184
+ num_words = len(words)
185
+
186
+ # Track decoding issues
187
+ decoding_info = {
188
+ "errors": [],
189
+ "warnings": [],
190
+ "forced_connections": [],
191
+ "disconnected_nodes": [],
192
+ "phase3_failures": [],
193
+ "phase4_force_connects": [],
194
+ }
195
+
196
+ # Get node types
197
+ node_types = [ID2NODE_TYPE.get(node_type_preds[i], "NominalConstant")
198
+ for i in range(num_words)]
199
+
200
+ # Convert logits to probabilities
201
+ arc_probs = self._sigmoid(arc_logits)
202
+ rel_probs = self._softmax(rel_logits, axis=-1)
203
+ root_probs = self._softmax(is_root_logits, axis=-1)[:, 1]
204
+
205
+ # Select root node
206
+ root_idx = int(np.argmax(root_probs))
207
+
208
+ # Build graph
209
+ graph = GPGraph()
210
+ graph.words = words
211
+
212
+ # Create all nodes
213
+ word_to_node = {}
214
+ for i, word in enumerate(words):
215
+ node = GPGPhraseNode(
216
+ ID=str(i),
217
+ spans=[(i, i)],
218
+ pos=node_types[i]
219
+ )
220
+ if child_of_whether_preds[i]:
221
+ node.child_of_whether = True
222
+ graph.add_node(node)
223
+ word_to_node[i] = node
224
+
225
+ # Track outgoing edges for each node (for pattern constraint checking)
226
+ node_outgoing_edges = {i: [] for i in range(num_words)}
227
+ # Track incoming edges for each node (for next_word constraint checking)
228
+ node_incoming_edges = {i: [] for i in range(num_words)}
229
+ # Track which nodes are targets of next_word edges
230
+ next_word_targets = set()
231
+ # Track graph structure for cycle detection
232
+ children_of = {i: set() for i in range(num_words)}
233
+
234
+ # Define constant types that require adjacent next_word edges
235
+ ADJACENT_ONLY_TYPES = {
236
+ "ModificationalConstant", "DeterminerConstant", "OtherConstant",
237
+ "NominalConstant", "SymbolConstant"
238
+ }
239
+ # Note: PunctuationalConstant is excluded (allows non-adjacent for paired punctuation)
240
+
241
+ # Phase 1: Collect all candidate edges with p(edge) > threshold
242
+ candidate_edges = []
243
+ for i in range(num_words):
244
+ for j in range(num_words):
245
+ if i == j:
246
+ continue
247
+ arc_prob = arc_probs[i, j]
248
+ if arc_prob > self.arc_threshold:
249
+ # Get label probabilities
250
+ for label_id in range(rel_probs.shape[2]):
251
+ label = self.id2label.get(label_id, "UNK")
252
+ rel_prob = rel_probs[i, j, label_id]
253
+ if rel_prob > 0.01: # Filter very low probability labels
254
+ candidate_edges.append({
255
+ "parent": i,
256
+ "child": j,
257
+ "label": label,
258
+ "label_id": label_id,
259
+ "arc_prob": arc_prob,
260
+ "rel_prob": rel_prob,
261
+ "score": arc_prob * rel_prob,
262
+ })
263
+
264
+ # Sort by score (descending)
265
+ candidate_edges.sort(key=lambda x: -x["score"])
266
+
267
+ # Helper function to check if adding edge would create a cycle
268
+ def would_create_cycle(parent: int, child: int) -> bool:
269
+ """Check if child can reach parent through existing edges (would create cycle)."""
270
+ visited = set()
271
+ stack = [child]
272
+ while stack:
273
+ node = stack.pop()
274
+ if node == parent:
275
+ return True
276
+ if node in visited:
277
+ continue
278
+ visited.add(node)
279
+ stack.extend(children_of[node])
280
+ return False
281
+
282
+ # Phase 2: Greedily select edges while respecting constraints
283
+ selected_edges = []
284
+
285
+ for edge in candidate_edges:
286
+ parent_idx = edge["parent"]
287
+ child_idx = edge["child"]
288
+ label = edge["label"]
289
+
290
+ # Constraint 1: No cycles (DAG constraint)
291
+ if would_create_cycle(parent_idx, child_idx):
292
+ continue
293
+
294
+ # Constraint 2: next_word adjacency constraint for *Constant types
295
+ if label == "next_word":
296
+ parent_type = node_types[parent_idx]
297
+ child_type = node_types[child_idx]
298
+ distance = abs(parent_idx - child_idx)
299
+
300
+ # For specified constant types, next_word must be adjacent
301
+ if parent_type in ADJACENT_ONLY_TYPES or child_type in ADJACENT_ONLY_TYPES:
302
+ if distance != 1:
303
+ continue
304
+
305
+ # Constraint 3: next_word target node constraints
306
+ if label == "next_word":
307
+ # 3a: If child already has non-next_word incoming edges, reject
308
+ non_next_word_incoming = [e for e in node_incoming_edges[child_idx] if e != "next_word"]
309
+ if non_next_word_incoming:
310
+ continue
311
+ else:
312
+ # 3b: If child is already a next_word target, only next_word outgoing allowed
313
+ if child_idx in next_word_targets:
314
+ continue
315
+
316
+ # Constraint 4: next_word targets can only have next_word outgoing edges
317
+ if parent_idx in next_word_targets and label != "next_word":
318
+ continue
319
+
320
+ # Constraint 5: Check if adding this edge violates pattern constraints
321
+ is_valid = self._is_edge_valid_for_pattern(
322
+ parent_idx, label, node_types[parent_idx], node_outgoing_edges[parent_idx],
323
+ is_root=(parent_idx == root_idx)
324
+ )
325
+ if not is_valid:
326
+ continue
327
+
328
+ # Edge is valid - add it
329
+ selected_edges.append(edge)
330
+ node_outgoing_edges[parent_idx].append(label)
331
+ node_incoming_edges[child_idx].append(label)
332
+ children_of[parent_idx].add(child_idx)
333
+
334
+ # Track next_word targets
335
+ if label == "next_word":
336
+ next_word_targets.add(child_idx)
337
+
338
+ # Add selected edges to graph with probability info
339
+ for edge in selected_edges:
340
+ parent_node = word_to_node[edge["parent"]]
341
+ child_node = word_to_node[edge["child"]]
342
+ gpg_edge = GPGEdge(label=edge["label"])
343
+ gpg_edge.arc_prob = edge["arc_prob"]
344
+ gpg_edge.rel_prob = edge["rel_prob"]
345
+ graph.add_edge(parent_node, child_node, gpg_edge)
346
+
347
+ # Phase 3: Connect disconnected nodes to ensure connected graph
348
+ # Find nodes reachable from root using BFS
349
+ def get_reachable_from(start_node: int) -> set:
350
+ reachable = set()
351
+ queue = [start_node]
352
+ reachable.add(start_node)
353
+ while queue:
354
+ node = queue.pop(0)
355
+ for child in children_of[node]:
356
+ if child not in reachable:
357
+ reachable.add(child)
358
+ queue.append(child)
359
+ return reachable
360
+
361
+ reachable = get_reachable_from(root_idx)
362
+
363
+ # Find unreachable nodes
364
+ unreachable = [i for i in range(num_words) if i not in reachable]
365
+
366
+ # Helper function for Phase 3 edge validation
367
+ def is_edge_valid_phase3(p_idx, c_idx, lbl):
368
+ """Check if edge is valid considering all constraints."""
369
+ # Constraint: next_word adjacency for *Constant types
370
+ if lbl == "next_word":
371
+ p_type = node_types[p_idx]
372
+ c_type = node_types[c_idx]
373
+ dist = abs(p_idx - c_idx)
374
+ if (p_type in ADJACENT_ONLY_TYPES or c_type in ADJACENT_ONLY_TYPES) and dist != 1:
375
+ return False
376
+ # next_word target constraints
377
+ non_nw_incoming = [e for e in node_incoming_edges[c_idx] if e != "next_word"]
378
+ if non_nw_incoming:
379
+ return False
380
+ else:
381
+ # Non-next_word edge cannot target a next_word target
382
+ if c_idx in next_word_targets:
383
+ return False
384
+ # next_word targets can only have next_word outgoing
385
+ if p_idx in next_word_targets and lbl != "next_word":
386
+ return False
387
+ # Pattern constraint
388
+ if not self._is_edge_valid_for_pattern(
389
+ p_idx, lbl, node_types[p_idx], node_outgoing_edges[p_idx],
390
+ is_root=(p_idx == root_idx)
391
+ ):
392
+ return False
393
+ return True
394
+
395
+ # Connect unreachable nodes to the main graph
396
+ while unreachable:
397
+ best_edge = None
398
+ best_score = -1
399
+ best_arc_prob = 0.0
400
+ best_rel_prob = 0.0
401
+
402
+ for node_idx in unreachable:
403
+ # Try connecting from any reachable node to this unreachable node
404
+ for parent_idx in reachable:
405
+ # Check cycle constraint first
406
+ if would_create_cycle(parent_idx, node_idx):
407
+ continue
408
+
409
+ arc_prob = arc_probs[parent_idx, node_idx]
410
+
411
+ # Enforce arc_threshold in Phase 3
412
+ if arc_prob < self.arc_threshold:
413
+ continue
414
+
415
+ best_label_id = int(np.argmax(rel_probs[parent_idx, node_idx]))
416
+ label = self.id2label.get(best_label_id, "UNK")
417
+ rel_prob = rel_probs[parent_idx, node_idx, best_label_id]
418
+
419
+ # Check pattern constraint
420
+ if not is_edge_valid_phase3(parent_idx, node_idx, label):
421
+ # Try other labels
422
+ found_valid = False
423
+ for lid in np.argsort(rel_probs[parent_idx, node_idx])[::-1]:
424
+ lbl = self.id2label.get(lid, "UNK")
425
+ if is_edge_valid_phase3(parent_idx, node_idx, lbl):
426
+ label = lbl
427
+ rel_prob = rel_probs[parent_idx, node_idx, lid]
428
+ found_valid = True
429
+ break
430
+ if not found_valid:
431
+ continue
432
+
433
+ score = arc_prob * rel_prob
434
+ if score > best_score:
435
+ best_score = score
436
+ best_edge = (parent_idx, node_idx, label)
437
+ best_arc_prob = float(arc_prob)
438
+ best_rel_prob = float(rel_prob)
439
+
440
+ if best_edge is not None:
441
+ parent_idx, child_idx, label = best_edge
442
+ parent_node = word_to_node[parent_idx]
443
+ child_node = word_to_node[child_idx]
444
+ gpg_edge = GPGEdge(label=label)
445
+ gpg_edge.arc_prob = best_arc_prob
446
+ gpg_edge.rel_prob = best_rel_prob
447
+ graph.add_edge(parent_node, child_node, gpg_edge)
448
+ node_outgoing_edges[parent_idx].append(label)
449
+ node_incoming_edges[child_idx].append(label)
450
+ children_of[parent_idx].add(child_idx)
451
+
452
+ # Track next_word targets
453
+ if label == "next_word":
454
+ next_word_targets.add(child_idx)
455
+
456
+ # Update reachable set
457
+ newly_reachable = get_reachable_from(child_idx)
458
+ reachable.update(newly_reachable)
459
+ unreachable = [i for i in range(num_words) if i not in reachable]
460
+ else:
461
+ # Try force connect to root
462
+ connected_any = False
463
+ best_root_edge = None
464
+ best_root_score = -1
465
+ best_root_arc_prob = 0.0
466
+ best_root_rel_prob = 0.0
467
+ best_root_label = None
468
+ best_root_node_idx = None
469
+
470
+ for node_idx in list(unreachable):
471
+ # Check cycle constraint
472
+ if would_create_cycle(root_idx, node_idx):
473
+ continue
474
+
475
+ arc_prob = float(arc_probs[root_idx, node_idx])
476
+
477
+ # Check arc_threshold for root connections
478
+ if arc_prob < self.arc_threshold:
479
+ continue
480
+
481
+ # Find best valid label
482
+ found_label = None
483
+ found_rel_prob = 0.0
484
+ for lid in np.argsort(rel_probs[root_idx, node_idx])[::-1]:
485
+ lbl = self.id2label.get(lid, "UNK")
486
+ if is_edge_valid_phase3(root_idx, node_idx, lbl):
487
+ found_label = lbl
488
+ found_rel_prob = float(rel_probs[root_idx, node_idx, lid])
489
+ break
490
+
491
+ if found_label is None:
492
+ continue
493
+
494
+ score = arc_prob * found_rel_prob
495
+ if score > best_root_score:
496
+ best_root_score = score
497
+ best_root_edge = True
498
+ best_root_arc_prob = arc_prob
499
+ best_root_rel_prob = found_rel_prob
500
+ best_root_label = found_label
501
+ best_root_node_idx = node_idx
502
+
503
+ if best_root_edge:
504
+ parent_node = word_to_node[root_idx]
505
+ child_node = word_to_node[best_root_node_idx]
506
+ gpg_edge = GPGEdge(label=best_root_label)
507
+ gpg_edge.arc_prob = best_root_arc_prob
508
+ gpg_edge.rel_prob = best_root_rel_prob
509
+ graph.add_edge(parent_node, child_node, gpg_edge)
510
+ node_outgoing_edges[root_idx].append(best_root_label)
511
+ node_incoming_edges[best_root_node_idx].append(best_root_label)
512
+ children_of[root_idx].add(best_root_node_idx)
513
+
514
+ # Track next_word targets
515
+ if best_root_label == "next_word":
516
+ next_word_targets.add(best_root_node_idx)
517
+
518
+ # Update reachable
519
+ newly_reachable = get_reachable_from(best_root_node_idx)
520
+ reachable.update(newly_reachable)
521
+ connected_any = True
522
+
523
+ if not connected_any:
524
+ msg = f"Phase 3: Cannot connect remaining {len(unreachable)} nodes with arc_prob >= {self.arc_threshold}"
525
+ decoding_info["phase3_failures"].append({
526
+ "message": msg,
527
+ "unreachable_nodes": list(unreachable),
528
+ "unreachable_words": [words[i] for i in unreachable if i < len(words)],
529
+ })
530
+ break
531
+
532
+ unreachable = [i for i in range(num_words) if i not in reachable]
533
+
534
+ # Phase 4: Force connect disconnected components to root branch
535
+ unreachable = [i for i in range(num_words) if i not in reachable]
536
+
537
+ if unreachable:
538
+ # Find connected components among unreachable nodes
539
+ def find_component(start_idx, nodes_set):
540
+ """Find all nodes in the same component as start_idx."""
541
+ component = set()
542
+ stack = [start_idx]
543
+ while stack:
544
+ node = stack.pop()
545
+ if node in component or node not in nodes_set:
546
+ continue
547
+ component.add(node)
548
+ # Follow outgoing edges
549
+ for child in children_of[node]:
550
+ if child in nodes_set:
551
+ stack.append(child)
552
+ # Follow incoming edges
553
+ for potential_parent in nodes_set:
554
+ if node in children_of[potential_parent]:
555
+ stack.append(potential_parent)
556
+ return component
557
+
558
+ def find_local_roots(component):
559
+ """Find nodes in component that have no incoming edges from within the component."""
560
+ local_roots = []
561
+ for node in component:
562
+ has_incoming_from_component = False
563
+ for potential_parent in component:
564
+ if node in children_of[potential_parent]:
565
+ has_incoming_from_component = True
566
+ break
567
+ if not has_incoming_from_component:
568
+ local_roots.append(node)
569
+ return local_roots if local_roots else list(component)
570
+
571
+ # Process disconnected components
572
+ remaining_unreachable = set(unreachable)
573
+ while remaining_unreachable:
574
+ start_node = next(iter(remaining_unreachable))
575
+ component = find_component(start_node, remaining_unreachable)
576
+ local_roots = find_local_roots(component)
577
+
578
+ # Try to connect any local root to the root branch
579
+ best_connection = None
580
+ best_score = -float('inf')
581
+
582
+ for local_root in local_roots:
583
+ for parent_idx in reachable:
584
+ if would_create_cycle(parent_idx, local_root):
585
+ continue
586
+
587
+ arc_prob = float(arc_probs[parent_idx, local_root])
588
+
589
+ # Find best valid label
590
+ for lid in np.argsort(rel_probs[parent_idx, local_root])[::-1]:
591
+ lbl = self.id2label.get(lid, "UNK")
592
+ if is_edge_valid_phase3(parent_idx, local_root, lbl):
593
+ rel_prob = float(rel_probs[parent_idx, local_root, lid])
594
+ score = arc_prob * rel_prob
595
+ if score > best_score:
596
+ best_score = score
597
+ best_connection = (parent_idx, local_root, lbl, arc_prob, rel_prob)
598
+ break
599
+
600
+ if best_connection:
601
+ parent_idx, child_idx, label, arc_prob, rel_prob = best_connection
602
+ parent_node = word_to_node[parent_idx]
603
+ child_node = word_to_node[child_idx]
604
+ gpg_edge = GPGEdge(label=label)
605
+ gpg_edge.arc_prob = arc_prob
606
+ gpg_edge.rel_prob = rel_prob
607
+ graph.add_edge(parent_node, child_node, gpg_edge)
608
+
609
+ node_outgoing_edges[parent_idx].append(label)
610
+ node_incoming_edges[child_idx].append(label)
611
+ children_of[parent_idx].add(child_idx)
612
+
613
+ if label == "next_word":
614
+ next_word_targets.add(child_idx)
615
+
616
+ # Update reachable set
617
+ newly_reachable = get_reachable_from(child_idx)
618
+ reachable.update(newly_reachable)
619
+ else:
620
+ # Force connect with any edge as last resort
621
+ best_force = None
622
+ best_arc = -1
623
+ for local_root in local_roots:
624
+ for parent_idx in reachable:
625
+ if would_create_cycle(parent_idx, local_root):
626
+ continue
627
+ arc_prob = float(arc_probs[parent_idx, local_root])
628
+ if arc_prob > best_arc:
629
+ best_arc = arc_prob
630
+ best_label_id = int(np.argmax(rel_probs[parent_idx, local_root]))
631
+ label = self.id2label.get(best_label_id, "UNK")
632
+ rel_prob = float(rel_probs[parent_idx, local_root, best_label_id])
633
+ best_force = (parent_idx, local_root, label, arc_prob, rel_prob)
634
+
635
+ if best_force:
636
+ parent_idx, child_idx, label, arc_prob, rel_prob = best_force
637
+ parent_node = word_to_node[parent_idx]
638
+ child_node = word_to_node[child_idx]
639
+ gpg_edge = GPGEdge(label=label)
640
+ gpg_edge.arc_prob = arc_prob
641
+ gpg_edge.rel_prob = rel_prob
642
+ graph.add_edge(parent_node, child_node, gpg_edge)
643
+
644
+ node_outgoing_edges[parent_idx].append(label)
645
+ node_incoming_edges[child_idx].append(label)
646
+ children_of[parent_idx].add(child_idx)
647
+
648
+ if label == "next_word":
649
+ next_word_targets.add(child_idx)
650
+
651
+ decoding_info["phase4_force_connects"].append({
652
+ "parent_idx": parent_idx,
653
+ "child_idx": child_idx,
654
+ "label": label,
655
+ })
656
+
657
+ newly_reachable = get_reachable_from(child_idx)
658
+ reachable.update(newly_reachable)
659
+ else:
660
+ decoding_info["errors"].append(f"Cannot connect component {component}")
661
+ decoding_info["disconnected_nodes"].extend(list(component))
662
+
663
+ remaining_unreachable -= component
664
+
665
+ # Check if there are any decoding issues
666
+ if decoding_info["errors"] or decoding_info["warnings"] or decoding_info["phase4_force_connects"]:
667
+ decoding_info["has_issues"] = True
668
+ else:
669
+ decoding_info["has_issues"] = False
670
+
671
+ return graph, decoding_info
672
+
673
+ def _is_edge_valid_for_pattern(
674
+ self,
675
+ parent_idx: int,
676
+ new_label: str,
677
+ node_type: str,
678
+ current_outgoing: List[str],
679
+ is_root: bool = False
680
+ ) -> bool:
681
+ """
682
+ Check if adding a new edge with the given label is valid for the node's pattern.
683
+ """
684
+ max_count = self._get_max_edge_count(node_type, new_label, is_root)
685
+ current_count = current_outgoing.count(new_label)
686
+ if current_count >= max_count:
687
+ return False
688
+ return True
689
+
690
+ def _get_max_edge_count(self, node_type: str, edge_label: str, is_root: bool = False) -> int:
691
+ """
692
+ Get the maximum allowed count for an edge label based on statistics.
693
+ """
694
+ patterns = None
695
+
696
+ # Check if we have statistics
697
+ if hasattr(self.stats, 'edge_pattern_counts') and self.stats.edge_pattern_counts:
698
+ if is_root:
699
+ key = ("ROOT", node_type)
700
+ patterns = self.stats.edge_pattern_counts.get(key, {})
701
+
702
+ if not patterns and hasattr(self.stats, 'node_type_pattern_counts'):
703
+ patterns = self.stats.node_type_pattern_counts.get(node_type, {})
704
+ elif hasattr(self.stats, 'node_type_pattern_counts') and self.stats.node_type_pattern_counts:
705
+ patterns = self.stats.node_type_pattern_counts.get(node_type, {})
706
+
707
+ if patterns:
708
+ max_count = 0
709
+ total = sum(patterns.values())
710
+ if total == 0:
711
+ return 1
712
+
713
+ cumulative = 0
714
+ for pattern, count in sorted(patterns.items(), key=lambda x: -x[1]):
715
+ pattern_counter = Counter(pattern)
716
+ label_count = pattern_counter.get(edge_label, 0)
717
+ max_count = max(max_count, label_count)
718
+
719
+ cumulative += count
720
+ if cumulative >= 0.95 * total:
721
+ break
722
+
723
+ if max_count > 0:
724
+ return max_count
725
+ return 1
726
+
727
+ # Fallback: use hard-coded rules
728
+ if edge_label == "func.arg":
729
+ if node_type == "ConjunctionalFunctor":
730
+ return 8
731
+ elif node_type == "ExpressionFunctor":
732
+ return 3
733
+ else:
734
+ return 1
735
+
736
+ return 1
737
+
738
+ def _sigmoid(self, x: np.ndarray) -> np.ndarray:
739
+ return 1 / (1 + np.exp(-np.clip(x, -500, 500)))
740
+
741
+ def _softmax(self, x: np.ndarray, axis: int = -1) -> np.ndarray:
742
+ x_max = np.max(x, axis=axis, keepdims=True)
743
+ exp_x = np.exp(x - x_max)
744
+ return exp_x / np.sum(exp_x, axis=axis, keepdims=True)
745
+
lingua/__init__.py ADDED
File without changes
lingua/concept/standard.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ LinguaGraphNodePoses = {
4
+ "AttributePredicator",
5
+ "AppositionalPredicator",
6
+ "FactualPredicator",
7
+ "LogicalPredicator",
8
+ "ReferentialPredicator",
9
+ "ConjunctionalFunctor",
10
+ "ExpressionFunctor",
11
+ "GeneralFunctor",
12
+ "ListFunctor",
13
+ "ModificationalFunctor",
14
+ "DeterminerConstant",
15
+ "InterjectionConstant",
16
+ "ModificationalConstant",
17
+ "NominalConstant",
18
+ "OtherConstant",
19
+ "PunctuationalConstant",
20
+ "SymbolConstant"
21
+ }
22
+
23
+ LinguaGraphAuxNodeLabels = {
24
+ "Apposition",
25
+ "Attribute",
26
+ "Copula",
27
+ "Discourse",
28
+ "Expression",
29
+ "List",
30
+ "Missing",
31
+ "Modification",
32
+ "Parataxis",
33
+ "Ref",
34
+ "Vocative",
35
+ "Whether",
36
+ }
37
+
38
+ LinguaGraphEdges = {
39
+ "body",
40
+ "variable",
41
+ "pred.arg.1",
42
+ "pred.arg.2",
43
+ "pred.arg.3",
44
+ "pred.arg.4",
45
+ "func.arg",
46
+ "appositive",
47
+ "attribute",
48
+ "discourse",
49
+ "index",
50
+ "modification",
51
+ "punctuation",
52
+ "ref",
53
+ "repeat",
54
+ "vocative",
55
+ }
56
+
57
+ LinguaGraphEdges.update( "as:" + edge for edge in list(LinguaGraphEdges))
58
+
59
+
lingua/learn/__init__.py ADDED
File without changes
lingua/learn/wordgraph/__init__.py ADDED
File without changes
lingua/learn/wordgraph/modeler/__init__.py ADDED
File without changes
lingua/learn/wordgraph/modeler/word2gp.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from graphlib import TopologicalSorter
2
+ from lingua.structure.gpgraph import GPGraph, GPGPhraseNode, GPGAuxNode, GPGEdge, GPGNode
3
+ from collections import defaultdict
4
+ import itertools
5
+ import logging
6
+ logger = logging.getLogger(__name__)
7
+
8
+ from lingua.utils.topology_sorter import LinguaGraphTopologySorter
9
+ from lingua.structure.utils import positions2spans
10
+ from lingua.structure.gpgraph import GPGraphVisualizer
11
+ visualizer = GPGraphVisualizer()
12
+
13
+ def edge2children(lingua_graph: GPGraph, visiting_node: GPGNode):
14
+ edge2children_map = defaultdict(list)
15
+ for child, edge in lingua_graph.children(visiting_node):
16
+ labels = tuple(edge.label.split("+"))
17
+ if len(labels) > 1 and not any("@" in label for label in labels):
18
+ raise ValueError(f"Unsupported edge label: {edge.label}")
19
+ # if len(labels) > 1 and any(label.startswith("as:") for label in labels[1:]):
20
+ # raise ValueError(f"Unsupported edge label: {edge.label}")
21
+ edge2children_map[labels].append(child)
22
+
23
+ for labels, children in edge2children_map.items():
24
+ if any("@" in label for label in labels):
25
+ assert len(children) == 1, f"Expected 1 child for edge {labels}, got {len(children)}"
26
+
27
+ return edge2children_map
28
+
29
+ symbol_label2edge = {
30
+ "Apposition": "@appositive",
31
+ "Attribute": "@attribute",
32
+ "Copula": "@copula",
33
+ "Discourse": "@discourse",
34
+ "Expression": "@expression",
35
+ "List": "@list",
36
+ "Missing": "@missing",
37
+ "Modification": "@modification",
38
+ "Parataxis": "@parataxis",
39
+ "Ref": "@ref",
40
+ "Vocative": "@vocative",
41
+ # "Whether": "@whether", # Whether is handled by property
42
+ }
43
+
44
+ symbol_edge2label = {edge: label for label, edge in symbol_label2edge.items()}
45
+
46
+
47
+ symbol_label2pos = {
48
+ "Apposition": "AppositionalPredicator",
49
+ "Attribute": "AttributePredicator",
50
+ "Copula": "FactualPredicator",
51
+ "Discourse": "ModificationalFunctor",
52
+ "Expression": "ExpressionFunctor",
53
+ "List": "ListFunctor",
54
+ "Missing": "FactualPredicator",
55
+ "Modification": "ModificationalFunctor",
56
+ "Parataxis": "ConjunctionalFunctor",
57
+ "Ref": "ReferentialPredicator",
58
+ "Vocative": "ModificationalFunctor",
59
+ "Whether": "GeneralFunctor", # Whether is handled by property
60
+ }
61
+
62
+
63
+ def recover_symbolic_nodes(lingua_graph: GPGraph, debug=False):
64
+ ordered_nodes = list(lingua_graph.topological_sort())
65
+
66
+ updated = False
67
+
68
+ for visiting_node in ordered_nodes:
69
+
70
+
71
+ if hasattr(visiting_node, "child_of_whether") and visiting_node.child_of_whether:
72
+ whether_parent = GPGAuxNode(label="Whether", pos="GeneralFunctor")
73
+ lingua_graph.add_node(whether_parent)
74
+
75
+ for parent, edge in list(lingua_graph.parents(visiting_node)):
76
+ # if edge.label.startswith("-"):
77
+ lingua_graph.remove_relation(parent, visiting_node)
78
+ lingua_graph.add_relation(parent, whether_parent, edge.label)
79
+
80
+ lingua_graph.add_relation(whether_parent, visiting_node, "func.arg")
81
+
82
+
83
+ edge2children_map = edge2children(lingua_graph, visiting_node)
84
+
85
+ if not any("@" in label for labels in edge2children_map.keys() for label in labels):
86
+ continue
87
+
88
+
89
+ # print("I'm processing edge2children_map: ", edge2children_map)
90
+
91
+
92
+ edges = sorted(edge2children_map.keys(), key=lambda x: x[0].count("@"), reverse=True)
93
+
94
+
95
+ # prefixes = ["@@@", "@@", "@"]
96
+
97
+ # for prefix in prefixes:
98
+ # for edge_labels in edges:
99
+ # if edge_labels[0].startswith(prefix):
100
+ # new_edge_label = edge_labels[0][len(prefix):]
101
+ # break
102
+
103
+ for edge_labels in edges:
104
+ # print("I'm processing edge: ", edge_labels)
105
+ if not any("@" in label for label in edge_labels):
106
+ continue
107
+
108
+ children = edge2children_map[edge_labels]
109
+ assert len(children) == 1, f"Expected 1 child for edge {edge_labels}, got {len(children)}"
110
+ child = children[0]
111
+
112
+ for this_edge_label in edge_labels:
113
+
114
+ if "@" not in this_edge_label:
115
+ continue
116
+
117
+ level = this_edge_label.count("@") - 1
118
+
119
+ if this_edge_label.startswith("as:"):
120
+ this_edge_label = this_edge_label[3:][level:]
121
+ reverse = True
122
+ else:
123
+ this_edge_label = this_edge_label[level:]
124
+ reverse = False
125
+
126
+ symbolic_node_label = symbol_edge2label[this_edge_label]
127
+ symoblic_node_pos = symbol_label2pos[symbolic_node_label]
128
+
129
+ symbolic_node = GPGAuxNode(label=symbolic_node_label, pos=symoblic_node_pos)
130
+ lingua_graph.add_node(symbolic_node)
131
+
132
+ if symoblic_node_pos == "ModificationalFunctor":
133
+
134
+
135
+ root = visiting_node
136
+
137
+ for parent, edge in list(lingua_graph.parents(root)):
138
+ if reverse and parent == visiting_node:
139
+ continue
140
+ #if edge.label.startswith("-"):
141
+ lingua_graph.remove_relation(parent, root)
142
+ lingua_graph.add_relation(parent, symbolic_node, edge.label)
143
+
144
+ variable, body = (child, visiting_node) if reverse else (visiting_node, child)
145
+
146
+ lingua_graph.add_relation(symbolic_node, variable, "variable")
147
+ lingua_graph.add_relation(symbolic_node, body, "body")
148
+
149
+ element_label = "@" * level + this_edge_label
150
+ edges_between = lingua_graph.get_edge(visiting_node, child).label.split("+")
151
+ assert any(element_label in label for label in edges_between), f"Expected {element_label} in {edges_between}"
152
+ left_edges_between = [label for label in edges_between if element_label not in label]
153
+
154
+ if not left_edges_between:
155
+ lingua_graph.remove_relation(visiting_node, child)
156
+ else:
157
+ lingua_graph.add_relation(visiting_node, child, "+".join(left_edges_between))
158
+
159
+ updated = True
160
+ elif symoblic_node_pos.endswith("Predicator"):
161
+
162
+
163
+ root = visiting_node
164
+
165
+ for parent, edge in list(lingua_graph.parents(root)):
166
+ if reverse and parent == visiting_node:
167
+ continue
168
+ #if edge.label.startswith("-"):
169
+ lingua_graph.remove_relation(parent, root)
170
+ lingua_graph.add_relation(parent, symbolic_node, edge.label)
171
+
172
+ arg1, arg2 = (child, visiting_node) if reverse else (visiting_node, child)
173
+
174
+ lingua_graph.add_relation(symbolic_node, arg1, "pred.arg.1")
175
+ lingua_graph.add_relation(symbolic_node, arg2, "pred.arg.2")
176
+
177
+ element_label = "@" * level + this_edge_label
178
+ edges_between = lingua_graph.get_edge(visiting_node, child).label.split("+")
179
+ assert any(element_label in label for label in edges_between), f"Expected {element_label} in {edges_between}"
180
+ left_edges_between = [label for label in edges_between if element_label not in label]
181
+
182
+ if not left_edges_between:
183
+ lingua_graph.remove_relation(visiting_node, child)
184
+ else:
185
+ lingua_graph.add_relation(visiting_node, child, "+".join(left_edges_between))
186
+
187
+ updated = True
188
+
189
+ elif symbolic_node_label in {"Parataxis", "List", "Expression"}:
190
+
191
+ element_label = "@" * level + this_edge_label
192
+
193
+ root = child if reverse else visiting_node
194
+ for parent, edge in list(lingua_graph.parents(root)):
195
+ if reverse and parent == visiting_node:
196
+ continue
197
+ #if edge.label.startswith("-"):
198
+ lingua_graph.remove_relation(parent, root)
199
+ lingua_graph.add_relation(parent, symbolic_node, edge.label)
200
+
201
+
202
+ elem_chain_node = visiting_node if reverse else child
203
+ elements = [child, visiting_node] if reverse else [visiting_node, child]
204
+ while True:
205
+
206
+ this_edge2children_map = edge2children(lingua_graph, elem_chain_node)
207
+ next_element = None
208
+ for labels in this_edge2children_map.keys():
209
+ if any(element_label in label for label in labels):
210
+ assert len(this_edge2children_map[labels]) == 1, f"Expected 1 child for edge {labels}, got {len(this_edge2children_map[labels])}"
211
+ next_element = this_edge2children_map[labels][0]
212
+ break
213
+ if not next_element:
214
+ break
215
+ elements.append(next_element)
216
+ elem_chain_node = next_element
217
+
218
+ for prev, next in itertools.pairwise(elements):
219
+ lingua_graph.add_relation(symbolic_node, prev, "func.arg")
220
+ lingua_graph.add_relation(symbolic_node, next, "func.arg")
221
+
222
+ edges_between = lingua_graph.get_edge(prev, next).label.split("+")
223
+ assert element_label in edges_between, f"Expected {element_label} in {edges_between}"
224
+ left_edges_between = [label for label in edges_between if label != element_label]
225
+
226
+ if not left_edges_between:
227
+ lingua_graph.remove_relation(prev, next)
228
+
229
+ updated = True
230
+
231
+ return lingua_graph, updated
232
+
233
+
234
+ def merge_multi_word_nodes(lingua_graph: GPGraph, debug=False):
235
+
236
+ ordered_nodes = list(lingua_graph.topological_sort())
237
+
238
+ updated = False
239
+ for visiting_node in ordered_nodes:
240
+
241
+ if not lingua_graph.has_node(visiting_node):
242
+ continue
243
+
244
+ edge2children_map = edge2children(lingua_graph, visiting_node)
245
+ if not any("next_word" in label for label in edge2children_map.keys()):
246
+ continue
247
+
248
+ children = edge2children_map[("next_word",)]
249
+ assert len(children) == 1, f"Expected 1 child for edge next_word, got {len(children)}"
250
+ child = children[0]
251
+
252
+ elem_chain_node = child
253
+ elements = [visiting_node, child]
254
+ while True:
255
+
256
+ this_edge2children_map = edge2children(lingua_graph, elem_chain_node)
257
+ if ("next_word",) in this_edge2children_map.keys():
258
+ next_element = this_edge2children_map[("next_word",)][0]
259
+ elements.append(next_element)
260
+ elem_chain_node = next_element
261
+ else:
262
+ break
263
+ node_words = []
264
+ for word_node in elements:
265
+ words = list(word_node.words(with_aux=False))
266
+ assert len(words) == 1, f"Expected 1 word for node {word_node}, got {len(words)}"
267
+ node_words.append(words[0])
268
+
269
+ new_node = GPGPhraseNode(spans=positions2spans(node_words), pos=visiting_node.pos)
270
+ lingua_graph.replace(visiting_node, new_node)
271
+
272
+ if hasattr(visiting_node, "child_of_whether") and visiting_node.child_of_whether:
273
+ new_node.child_of_whether = True
274
+
275
+ for n in elements[1:]:
276
+ lingua_graph.remove_node(n)
277
+
278
+ updated = True
279
+
280
+ return lingua_graph, updated
281
+
282
+
283
+ def wordlingua2lingua(lingua_graph: GPGraph, debug=False):
284
+
285
+ lingua_graph, updated1 = merge_multi_word_nodes(lingua_graph, debug=debug)
286
+ lingua_graph, updated2 = recover_symbolic_nodes(lingua_graph, debug=debug)
287
+
288
+ return lingua_graph, updated1 or updated2
289
+
290
+
lingua/structure/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Structure package
lingua/structure/basegraph.py ADDED
@@ -0,0 +1,887 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Graph data problem designed for graph2graph learning
3
+ """
4
+ from typing import List
5
+
6
+ import networkx as nx
7
+
8
+ class Node:
9
+ """
10
+ Node
11
+ """
12
+
13
+
14
+ # def __init__(self, ID=None):
15
+ # """
16
+ #
17
+ # :param id:
18
+ # :param object:
19
+ # :param rep:
20
+ # :param state:
21
+ # :param prob:
22
+ # """
23
+ #
24
+ # self.ID = ID
25
+
26
+ @property
27
+ def ID(self):
28
+ """
29
+
30
+ :return:
31
+ :rtype:
32
+ """
33
+
34
+ pass
35
+
36
+ @ID.setter
37
+ def ID(self, id):
38
+ """
39
+
40
+ :param id:
41
+ :type id:
42
+ :return:
43
+ :rtype:
44
+ """
45
+ pass
46
+
47
+
48
+ def __hash__(self):
49
+ """
50
+
51
+ :return:
52
+ """
53
+ return hash(self.ID)
54
+
55
+ def __eq__(self, another):
56
+ """
57
+
58
+ :param another:
59
+ :return:
60
+ """
61
+ return self.ID == another.ID
62
+
63
+
64
+ class Edge(object):
65
+ """
66
+ Edge
67
+ """
68
+
69
+ def __init__(self, start=None, end=None):
70
+ """
71
+
72
+ :param object:
73
+ :param rep:
74
+ :param state:
75
+ :param prob:
76
+ """
77
+
78
+ self.start = start
79
+ self.end = end
80
+
81
+
82
+ class Graph(object):
83
+ """
84
+ Graph
85
+ """
86
+
87
+ def __init__(self, g=None):
88
+ """
89
+ init graph
90
+ """
91
+ super().__init__()
92
+ if g is None:
93
+ self.g = nx.Graph()
94
+ self.node_id_base = 0
95
+ else:
96
+ import copy
97
+ assert (isinstance(g, nx.Graph) or isinstance(g, Graph))
98
+ if isinstance(g, Graph):
99
+ self.g = copy.deepcopy(g.g)
100
+ self.node_id_base = g.node_id_base
101
+ else:
102
+ self.g = copy.deepcopy(g)
103
+ self.node_id_base = max(g.nodes, default=0) + 1
104
+
105
+ def nodes(self):
106
+ """
107
+
108
+ :return:
109
+ """
110
+
111
+ for node in self.g.nodes:
112
+
113
+ yield self.get_node(node)
114
+
115
+ def edges(self):
116
+ """
117
+
118
+ :return:
119
+ """
120
+
121
+ for s, e in self.g.edges():
122
+ edge = self.g[s][e]["Edge"]
123
+
124
+ s_node = self.get_node(s)
125
+ e_node = self.get_node(e)
126
+
127
+ yield (s_node, edge, e_node)
128
+
129
+ def has_node(self, node):
130
+ """
131
+
132
+ :param node:
133
+ :return:
134
+ """
135
+
136
+ return node.ID in self.g
137
+
138
+ def has_edge(self, node1, node2):
139
+ """
140
+
141
+ :param node1:
142
+ :param node2:
143
+ :return:
144
+ """
145
+
146
+ return node2.ID in self.g[node1.ID]
147
+
148
+ def number_of_nodes(self):
149
+ """
150
+
151
+ :return:
152
+ """
153
+
154
+ return nx.number_of_nodes(self.g)
155
+
156
+ def number_of_edges(self):
157
+ """
158
+
159
+ :return:
160
+ """
161
+
162
+ return nx.number_of_edges(self.g)
163
+
164
+
165
+ def get_node(self, node_id):
166
+ """
167
+
168
+ :param node_id:
169
+ :return:
170
+ """
171
+
172
+ return self.g.nodes[node_id]["Node"]
173
+
174
+ def remove_node(self, node):
175
+ """
176
+
177
+ :param node:
178
+ :return:
179
+ """
180
+ self.g.remove_node(node.ID)
181
+
182
+ def remove_edge(self, edge):
183
+ """
184
+
185
+ :param node:
186
+ :return:
187
+ """
188
+ self.g.remove_edge(edge.start, edge.end)
189
+
190
+ def remove_edge_between(self, node1, node2):
191
+ """
192
+
193
+ :param node1:
194
+ :type node1:
195
+ :param node2:
196
+ :type node2:
197
+ :return:
198
+ :rtype:
199
+ """
200
+ if self.g.has_edge(node1.ID, node2.ID):
201
+ self.g.remove_edge(node1.ID, node2.ID)
202
+
203
+ def get_edge(self, node1, node2):
204
+ """
205
+
206
+ :param node1_id:
207
+ :param node2_id:
208
+ :return:
209
+ """
210
+
211
+ if isinstance(node1, Node):
212
+ node1 = node1.ID
213
+ if isinstance(node2, Node):
214
+ node2 = node2.ID
215
+ """
216
+ if type(node1) is not int:
217
+ node1 = node1.ID
218
+ if type(node2) is not int:
219
+ node2 = node2.ID
220
+ """
221
+
222
+ try:
223
+ edge = self.g[node1][node2]["Edge"]
224
+ except KeyError as e:
225
+ raise Exception("There is no edge between node {0} and {1}".format(node1, node2))
226
+
227
+ return edge
228
+
229
+ def add_node(self, n, reuse_id=False):
230
+ """
231
+
232
+ :param n:
233
+ :param id:
234
+ :return:
235
+ """
236
+
237
+ if reuse_id:
238
+ node_id = n.ID
239
+ else:
240
+ node_id = self.node_id_base
241
+ self.node_id_base += 1
242
+
243
+ n.ID = node_id
244
+
245
+ self.g.add_node(node_id, Node=n)
246
+
247
+ return n
248
+
249
+ def add_edge(self, ni, nj, e):
250
+ """
251
+
252
+ :param ni:
253
+ :param eij:
254
+ :param nj:
255
+ :return:
256
+ """
257
+
258
+ if not isinstance(ni, Node):
259
+ ni = self.get_node(ni)
260
+ if not isinstance(nj, Node):
261
+ nj = self.get_node(nj)
262
+
263
+ e.start = ni.ID
264
+ e.end = nj.ID
265
+
266
+ self.g.add_edge(ni.ID, nj.ID, Edge=e)
267
+
268
+ def neighbors(self, node):
269
+ """
270
+
271
+ :param ni:
272
+ :return:
273
+ """
274
+
275
+ for nj in self.g[node.ID]:
276
+
277
+ eij = self.g[node.ID][nj]["Edge"]
278
+
279
+ yield eij, self.get_node(nj)
280
+
281
+
282
+ def connected_components(self):
283
+ """
284
+
285
+ :return:
286
+ """
287
+ components = nx.algorithms.components.connected_components(self.g)
288
+
289
+ for component in components:
290
+ yield [self.get_node(x) for x in component]
291
+
292
+ def breadth_first_dag(self, start_node):
293
+ """
294
+
295
+ :return:
296
+ """
297
+
298
+ dag = DirectedGraph()
299
+
300
+ for node in self.nodes():
301
+
302
+ dag.add_node(node.copy(), reuse_id=True)
303
+
304
+ edges = nx.bfs_edges(self.g, start_node.ID)
305
+ orderd_nodes = [start_node.ID] + [v for u, v in edges]
306
+ for i, u in enumerate(orderd_nodes):
307
+ for j, v in enumerate(orderd_nodes):
308
+
309
+ if j <= i:
310
+ continue
311
+ node_u = self.get_node(u)
312
+ node_v = self.get_node(v)
313
+
314
+ if self.has_edge(node_u, node_v):
315
+ edge = self.get_edge(node_u, node_v).copy()
316
+ dag.add_edge(node_u, node_v, edge)
317
+ assert self.number_of_nodes() == dag.number_of_nodes()
318
+ assert self.number_of_edges() == dag.number_of_edges()
319
+
320
+ return dag
321
+
322
+ def breadth_first_tree(self, start_node):
323
+ """
324
+
325
+ :return:
326
+ """
327
+
328
+ dag = DirectedGraph()
329
+
330
+ dag.add_node(start_node.copy(), reuse_id=True)
331
+
332
+ edges = nx.bfs_edges(self.g, start_node.ID)
333
+
334
+ def __get_or_copy_node(u):
335
+
336
+ try:
337
+ node_u = dag.get_node(u)
338
+ except:
339
+ node_u = self.get_node(u).copy()
340
+ dag.add_node(node_u, reuse_id=True)
341
+ return node_u
342
+
343
+ for u, v in edges:
344
+ node_u = __get_or_copy_node(u)
345
+ node_v = __get_or_copy_node(v)
346
+
347
+ edge = self.get_edge(u, v)
348
+ dag.add_edge(node_u, node_v, edge)
349
+
350
+ return dag
351
+
352
+ def __copy__(self):
353
+ """
354
+
355
+ :return:
356
+ """
357
+ copied = type(self)()
358
+ copied.g = self.g.copy()
359
+ copied.node_id_base = self.node_id_base
360
+ return copied
361
+
362
+ def __deepcopy__(self, memodict={}):
363
+ """
364
+
365
+ :param memodict:
366
+ :type memodict:
367
+ :return:
368
+ :rtype:
369
+ """
370
+
371
+ from copy import deepcopy
372
+
373
+ # copied_g = type(self.g)()
374
+ #
375
+ copied = type(self)()
376
+
377
+ memodict[id(self)] = copied
378
+
379
+ for node in self.nodes():
380
+ new_node = deepcopy(node)
381
+ new_node = copied.add_node(new_node, reuse_id=True)
382
+ assert new_node.ID == node.ID, "Node ID is not copied correctly {0} {1}".format(new_node.ID, node.ID)
383
+
384
+ for (s_node, edge, e_node) in self.edges():
385
+ copied.add_edge(s_node, e_node, deepcopy(edge))
386
+
387
+ copied.node_id_base = self.node_id_base
388
+ return copied
389
+
390
+ def offsprings(self, node, filter=None):
391
+ """
392
+
393
+ :param node:
394
+ :return:
395
+ """
396
+
397
+ for node_id in nx.dfs_postorder_nodes(self.g, node.ID):
398
+ node = self.get_node(node_id)
399
+ if not filter or filter(node):
400
+ yield self.get_node(node_id)
401
+
402
+ def subgraph(self, nodes):
403
+ """
404
+
405
+ :param nodes:
406
+ :return:
407
+ """
408
+ node_ids = [n.ID if isinstance(n, Node) else n for n in nodes]
409
+
410
+ subgraph = self.g.subgraph(node_ids).copy()
411
+
412
+ result = self.__class__()
413
+ result.g = subgraph
414
+
415
+ return result
416
+
417
+ def has_path(self, node1, node2):
418
+ """
419
+
420
+ :param node1:
421
+ :param node2:
422
+ :return:
423
+ """
424
+ return nx.algorithms.shortest_paths.has_path(self.g, node1.ID, node2.ID)
425
+
426
+
427
+ def dual(self):
428
+ """
429
+ return the dual graph
430
+ the dual graph is the graph with edges corresponding nodes and
431
+ nodes corresponding edges
432
+ """
433
+
434
+ dual = Graph()
435
+
436
+ edge_node_map = dict()
437
+
438
+ for edge in self.edges():
439
+
440
+ node = Node(value=edge.value)
441
+
442
+ dual.add_node(node)
443
+
444
+ edge_node_map[(edge.start, edge.end)] = node
445
+ edge_node_map[(edge.end, edge.start)] = node
446
+
447
+ for node in self.nodes():
448
+
449
+ edges = list(self.g.edges(node.ID))
450
+
451
+ # since the end node is added
452
+ assert len(edges) >= 2, "Edge number should larger than 2 " \
453
+ "since the end node is added"
454
+
455
+ for idx1, (edge1_start, edge1_end) in enumerate(edges):
456
+
457
+ for (edge2_start, edge2_end) in edges[idx1 + 1:]:
458
+
459
+ node1 = edge_node_map[(edge1_start, edge1_end)]
460
+ node2 = edge_node_map[(edge2_start, edge2_end)]
461
+
462
+ dual.add_edge(node1, node2, Edge(value=node.value))
463
+
464
+ return dual
465
+
466
+ #
467
+ # def visualize(self, file_name=None):
468
+ # """
469
+ #
470
+ # :return:
471
+ # """
472
+ #
473
+ # visual_g = type(self.g)()
474
+ #
475
+ # for node in self.nodes():
476
+ # visual_g.add_node(node.ID, label=self.node_label(node))
477
+ #
478
+ # for node_s, edge, node_e in self.edges():
479
+ #
480
+ # visual_g.add_edge(node_s.ID, node_e.ID, label=self.edge_label(edge))
481
+ #
482
+ # from networkx.drawing.nx_agraph import graphviz_layout, to_agraph
483
+ #
484
+ # A = to_agraph(visual_g)
485
+ # if file_name:
486
+ # A.draw(file_name, prog="dot")
487
+ #
488
+ # return A.to_string()
489
+
490
+
491
+
492
+ class DirectedGraph(Graph):
493
+ """
494
+ Directed Graph
495
+ """
496
+
497
+ def __init__(self, g=None):
498
+ """
499
+
500
+ :param edge_identifier:
501
+ """
502
+
503
+ if g is None:
504
+ g = nx.DiGraph()
505
+
506
+ super().__init__(g=g)
507
+
508
+ def is_connected(self):
509
+ """
510
+
511
+ :return:
512
+ """
513
+ return nx.algorithms.components.is_weakly_connected(self.g)
514
+
515
+
516
+ def connected_components(self):
517
+ """
518
+
519
+ :return:
520
+ """
521
+ components = nx.algorithms.components.weakly_connected_components(self.g)
522
+
523
+ for component in components:
524
+ yield [self.get_node(x) for x in component]
525
+
526
+ def is_leaf(self, node):
527
+ if len(list(self.children(node))) == 0:
528
+ return True
529
+ return False
530
+
531
+ def children(self, node):
532
+ """
533
+
534
+ :param node:
535
+ :return:
536
+ """
537
+ for child_id in self.g.successors(node.ID):
538
+ child = self.get_node(child_id)
539
+ rel = self.get_edge(node, child)
540
+
541
+ yield child, rel
542
+
543
+ def offsprings(self, node, filter=None):
544
+ """
545
+
546
+ :param node:
547
+ :return:
548
+ """
549
+ yield node
550
+ for node_id in nx.descendants(self.g, node.ID):
551
+ node = self.get_node(node_id)
552
+ if not filter or filter(node):
553
+ yield self.get_node(node_id)
554
+
555
+ def ancestors(self, node, filter=None):
556
+ """
557
+
558
+ :param node:
559
+ :return:
560
+ """
561
+ yield node
562
+ for node_id in nx.ancestors(self.g, node.ID):
563
+ node = self.get_node(node_id)
564
+ if not filter or filter(node):
565
+ yield self.get_node(node_id)
566
+
567
+ def parents(self, node):
568
+ """
569
+
570
+ :param node:
571
+ :return:
572
+ """
573
+ for parent_id in self.g.predecessors(node.ID):
574
+ parent = self.get_node(parent_id)
575
+ rel = self.get_edge(parent, node)
576
+
577
+ yield parent, rel
578
+
579
+ def topological_sort(self):
580
+ """
581
+
582
+ :return:
583
+ """
584
+
585
+ for id in nx.topological_sort(self.g):
586
+ yield self.get_node(id)
587
+
588
+
589
+ class LearnableGraph(object):
590
+ """
591
+ LearnableGraph
592
+ """
593
+
594
+ def __init__(self, *args, **kwargs):
595
+ super().__init__(*args, **kwargs)
596
+
597
+
598
+ def node_types(self, orders: List[Node], node_voc_functor):
599
+ """
600
+
601
+ :return:
602
+ :rtype:
603
+ """
604
+
605
+ import numpy as np
606
+
607
+ return np.narray([node_voc_functor(x) for x in orders])
608
+
609
+
610
+ def adjmatrix(self, node_orders: List[Node], edge_voc_functor, empty_id=0):
611
+ """
612
+
613
+ :return:
614
+ :rtype:
615
+ """
616
+
617
+ n_nodes = len(node_orders)
618
+ node2index = dict((node, idx) for idx, node in enumerate(node_orders))
619
+ import numpy as np
620
+
621
+ in_a = np.ones([n_nodes, n_nodes], dtype=np.int32) * empty_id
622
+ out_a = np.ones([n_nodes, n_nodes], dtype=np.int32) * empty_id
623
+
624
+ for u, edge, v in self.edges():
625
+
626
+ u_idx = node2index[u]
627
+ v_idx = node2index[v]
628
+
629
+ e_idx = edge_voc_functor(edge) # zero is empty type
630
+
631
+ out_a[u_idx][v_idx] = e_idx
632
+ in_a[v_idx][u_idx] = e_idx
633
+
634
+ if not nx.is_directed(self.g):
635
+ in_a[u_idx][v_idx] = e_idx
636
+ out_a[v_idx][u_idx] = e_idx
637
+
638
+ return (in_a, out_a)
639
+
640
+ def to_tensor(self, node_orders: List[Node], node_voc, edge_voc, end_node=None):
641
+ """
642
+
643
+ :return:
644
+ """
645
+ node_types = self.node_types(node_orders, node_voc)
646
+ a_in, a_out = self.adjmatrix(node_orders, edge_voc)
647
+ if end_node:
648
+ node_num = len(node_types)
649
+ node_types.resize((node_num + 1,))
650
+ node_types[-1] = end_node
651
+
652
+ a_in.resize((node_num + 1, node_num + 1))
653
+ a_out.resize((node_num + 1, node_num + 1))
654
+
655
+
656
+ return node_types, a_in, a_out
657
+
658
+
659
+
660
+ def valid_alignment(choices):
661
+ """
662
+
663
+ :param choices:
664
+ :return:
665
+ """
666
+ def _inner(i):
667
+ if i == n:
668
+ yield tuple(result)
669
+ return
670
+ for elt in sets[i] - seen:
671
+ seen.add(elt)
672
+ result[i] = elt
673
+ for t in _inner(i + 1):
674
+ yield t
675
+ seen.remove(elt)
676
+
677
+ sets = [set(seq) for seq in choices]
678
+ n = len(sets)
679
+ seen = set()
680
+ result = [None] * n
681
+ for t in _inner(0):
682
+ yield t
683
+
684
+
685
+ def is_valid_topology_sort(dag, node_objs):
686
+ """
687
+ decide whether the order of nodes in dag2 is a valid topological sort order of dag1
688
+ :param dag:
689
+ :param pred_node_objs donot contain the start node:
690
+ :return:
691
+ """
692
+ target_nodes = list(dag.nodes())
693
+ target_node_objects = [n.object for n in target_nodes]
694
+
695
+ choices = []
696
+ for i, node_obj in enumerate(node_objs):
697
+ cur_choice = []
698
+ for j, target_node in enumerate(target_node_objects):
699
+ if target_node == node_obj:
700
+ cur_choice.append(j)
701
+
702
+ if len(cur_choice) == 0:
703
+ return False
704
+
705
+ choices.append(cur_choice)
706
+
707
+ for align in valid_alignment(choices):
708
+
709
+ if len(set(align)) != len(align):
710
+ continue
711
+
712
+ node_ids = [target_nodes[i].ID for i in align]
713
+
714
+ bad_align = False
715
+ for id, node_id in enumerate(node_ids):
716
+
717
+ if nx.descendants(dag.g, node_id).intersection(set(node_ids[:id])):
718
+ bad_align = True
719
+ break
720
+
721
+ if nx.ancestors(dag.g, node_id).intersection(set(node_ids[id + 1:])):
722
+ bad_align = True
723
+ break
724
+
725
+ if not bad_align:
726
+ return True
727
+
728
+ return False
729
+
730
+
731
+
732
+
733
+ def not_isomorphic(graph_a, graph_b):
734
+ """
735
+
736
+ :param graph_a:
737
+ :param graph_b:
738
+ :return:
739
+ """
740
+
741
+ return nx.faster_could_be_isomorphic(graph_a.g, graph_b.g)
742
+
743
+
744
+ def dot2image(dot_string, file_name=None, program="dot", format=None, return_img=False):
745
+ """
746
+
747
+ @param g:
748
+ @param file_name:
749
+ @return:
750
+ """
751
+
752
+ from PIL import Image
753
+ import os
754
+
755
+ import tempfile
756
+ dot_file = tempfile.NamedTemporaryFile(mode='w', suffix=".dot", delete=False)
757
+ dot_file.write(dot_string)
758
+ dot_file.close()
759
+
760
+ if not format:
761
+ format = "svg"
762
+
763
+ if not file_name and return_img:
764
+ import tempfile
765
+ fout = tempfile.NamedTemporaryFile(suffix="." + format)
766
+ file_name = fout.name
767
+
768
+ return_val = os.system(f'{program} -T {format} "{dot_file.name}" -o "{file_name}"')
769
+ assert return_val == 0
770
+
771
+ if return_img:
772
+ return Image.open(file_name)
773
+
774
+ class GraphVisualizer(object):
775
+ """
776
+ BasicGraphVisualizer
777
+ """
778
+
779
+
780
+ def node_label(self, graph, node, *args, **kwargs):
781
+ """
782
+
783
+ :param node:
784
+ :type node:
785
+ :return:
786
+ :rtype:
787
+ """
788
+
789
+ return str(node)
790
+
791
+ def node_style(self, graph, node, *args, **kwargs):
792
+ """
793
+
794
+ @param graph:
795
+ @param node:
796
+ @param args:
797
+ @param kwargs:
798
+ @return:
799
+ """
800
+ return {}
801
+
802
+ def edge_label(self, graph, edge, *args, **kwargs):
803
+ """
804
+
805
+ :param edge:
806
+ :type edge:
807
+ :return:
808
+ :rtype:
809
+ """
810
+ return str(edge)
811
+
812
+ def edge_style(self, graph, edge, *args, **kwargs):
813
+ """
814
+
815
+ @param graph:
816
+ @param edge:
817
+ @param args:
818
+ @param kwargs:
819
+ @return:
820
+ """
821
+
822
+ return {}
823
+
824
+ def visualize(self, graph, file_name=None, return_img=False, format="svg", no_text=False, *args, **kwargs):
825
+ """
826
+
827
+ @return:
828
+ @rtype:
829
+ """
830
+ import io
831
+ dot_string = io.StringIO()
832
+
833
+ dot_string.write("strict digraph {\n")
834
+
835
+ node2index = dict()
836
+ for index, node_id in enumerate(graph.g.nodes()):
837
+ node = graph.get_node(node_id)
838
+
839
+ node_label = self.node_label(graph, node, no_text=no_text, *args, **kwargs)
840
+ node_style = self.node_style(graph, node, *args, **kwargs)
841
+ node2index[node.ID] = index
842
+
843
+ node_attr = ['label="{0}"'.format(node_label)]
844
+ for k, v in node_style.items():
845
+ node_attr.append('{0}="{1}"'.format(k, v))
846
+
847
+ vis_node_label = '{0}\t[{1}]; \n'.format(
848
+ index, ", ".join(node_attr)
849
+ )
850
+
851
+ dot_string.write(vis_node_label)
852
+ # if simple:
853
+ # g.add_node(id2index[node_id], label=node_text, shape=shape)
854
+ # else:
855
+ # g.add_node(node_id, label=node_text, shape=shape)
856
+
857
+ for s, e in graph.g.edges():
858
+ edge = graph.g[s][e]["Edge"]
859
+
860
+ edge_label = self.edge_label(graph, edge, *args, **kwargs)
861
+ edge_style = self.edge_style(graph, edge, *args, **kwargs)
862
+
863
+ edge_attr = ['label="{0}"'.format(edge_label)]
864
+ for k, v in edge_style.items():
865
+ edge_attr.append('{0}="{1}"'.format(k, v))
866
+
867
+ s = node2index[s]
868
+ e = node2index[e]
869
+
870
+ dot_string.write('{0}\t->\t{1}\t[{2}];\n'.format(
871
+ s, e, ", ".join(edge_attr)
872
+ ))
873
+
874
+ dot_string.write("}\n")
875
+
876
+ dot_string = dot_string.getvalue()
877
+
878
+ result = dot_string
879
+
880
+ if file_name or return_img:
881
+ image = dot2image(dot_string, file_name=file_name, return_img=return_img,
882
+ format=format)
883
+
884
+ if return_img:
885
+ result = image
886
+
887
+ return result
lingua/structure/gpgraph.py ADDED
@@ -0,0 +1,1683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ oia graph
3
+ """
4
+ # import numpy as np
5
+
6
+ # logger = logging.getLogger(__name__)
7
+ import copy
8
+ import json
9
+
10
+ import re
11
+ from enum import Enum
12
+ from typing import Union
13
+
14
+ from .basegraph import Node, Edge, DirectedGraph, LearnableGraph, GraphVisualizer
15
+ from .utils import positions2spans, CompactJSONEncoder
16
+
17
+ arg_placeholder_pattern = re.compile(r'{\d+}')
18
+
19
+ def sent_spans2list(spans):
20
+ spans_list = list()
21
+ for span in spans:
22
+ if isinstance(span, str):
23
+ spans_list.append({'label': span})
24
+ else:
25
+ assert isinstance(span, tuple) and len(span) == 2
26
+ spans_list.append({'start': span[0], 'end': span[1]})
27
+ return spans_list
28
+
29
+ def is_arg_placeholder(string):
30
+ """
31
+
32
+ @param string:
33
+ @return:
34
+ """
35
+ return re.match(arg_placeholder_pattern, string) is not None
36
+
37
+
38
+
39
+ class GPGNode(Node):
40
+ """
41
+ GPGNode
42
+ """
43
+
44
+ def __init__(self, id=None, pos=None, confidence=None, *args, **kwargs):
45
+
46
+ self.id = id
47
+ self.pos = pos
48
+ self.confidence = confidence
49
+
50
+ @property
51
+ def ID(self):
52
+ """
53
+
54
+ :return:
55
+ """
56
+ return self.id
57
+
58
+ @ID.setter
59
+ def ID(self, id):
60
+ """
61
+ setter
62
+ """
63
+ self.id = id
64
+
65
+ def __hash__(self):
66
+ """
67
+
68
+ :return:
69
+ """
70
+ return hash(self.ID)
71
+
72
+ def __eq__(self, another):
73
+ """
74
+
75
+ :param another:
76
+ :return:
77
+ """
78
+ return self.ID == another.ID
79
+
80
+ def copy(self):
81
+ return copy.deepcopy(self)
82
+
83
+
84
+ def get_start(x):
85
+ if isinstance(x, (tuple, list)):
86
+ return x[0]
87
+ elif isinstance(x, int):
88
+ return x
89
+ else:
90
+ raise ValueError('unexpected span')
91
+
92
+ def standardize_spans(spans):
93
+ """
94
+
95
+ @param spans:
96
+ @type spans:
97
+ @return:
98
+ @rtype:
99
+ """
100
+ standardized = []
101
+ # deduplicated = []
102
+ # span_set = set()
103
+ # for span in spans:
104
+ # if isinstance(span, int):
105
+ # span = (span, span)
106
+ # if tuple(span) not in span_set:
107
+ # deduplicated.append(span)
108
+ # span_set.add(tuple(span))
109
+ # else:
110
+ # continue
111
+
112
+ # spans = deduplicated
113
+
114
+ idx = 0
115
+ while idx < len(spans):
116
+ span = spans[idx]
117
+ if isinstance(span, int):
118
+ standardized.append((span, span))
119
+ elif isinstance(span, str):
120
+ standardized.append(span)
121
+ # elif isinstance(span, tuple) and isinstance(span[0], str):
122
+ # standardized.append(span[0])
123
+ elif isinstance(span, (tuple, list)):
124
+ assert len(span) == 2
125
+ standardized.append(tuple(span))
126
+ # we merge next span if it is continuous
127
+ # to_merge = idx
128
+ # break_continuous = False
129
+ # for j in range(idx + 1, len(spans)):
130
+ # if not isinstance(spans[j], (tuple, list)):
131
+ # break
132
+ # if spans[j][0] == spans[j-1][1] + 1 and not break_continuous:
133
+ # to_merge = j
134
+ # else:
135
+ # break_continuous = True
136
+ #
137
+ # merged_span = (span[0], spans[to_merge][1])
138
+ # idx += to_merge - idx
139
+ # standardized.append(tuple(merged_span))
140
+ else:
141
+ raise ValueError('Invalid span: {}'.format(span))
142
+ idx += 1
143
+
144
+ return tuple(standardized)
145
+
146
+
147
+ def readable_spans(spans):
148
+ """
149
+
150
+ @param spans:
151
+ @type spans:
152
+ @return:
153
+ @rtype:
154
+ """
155
+
156
+ readable = []
157
+ for span in spans:
158
+ if isinstance(span, int):
159
+ readable.append(span)
160
+ elif isinstance(span, str):
161
+ readable.append(span)
162
+ else:
163
+ start, end = span
164
+ if start == end:
165
+ span = start
166
+
167
+ readable.append(span)
168
+
169
+ return tuple(readable)
170
+
171
+
172
+ class GPGPhraseNode(GPGNode):
173
+ """
174
+ GPGPhraseNode
175
+ """
176
+
177
+ def __init__(self, spans=None, id=None, pos=None, confidence=None, *args, **kwargs):
178
+ super().__init__(id=id, pos=pos, confidence=confidence, *args, **kwargs)
179
+
180
+ if spans is not None:
181
+ self._spans = standardize_spans(spans)
182
+ else:
183
+ self._spans = None
184
+ self.contexts = list()
185
+ #
186
+ # @staticmethod
187
+ # def merge_by_char(spans):
188
+ # if any(isinstance(x, str) for x in spans):
189
+ # std_span = OIAWordsNode.merge_continuous_spans(spans)
190
+ # return std_span
191
+ # std_span = list()
192
+ # for span in spans:
193
+ # for i in range(span[0], span[1] + 1):
194
+ # std_span.append(i)
195
+ # std_span = list(set(std_span))
196
+ # std_span = OIAWordsNode.sort_non_str_spans(std_span)
197
+ # std_span = OIAWordsNode.merge_continuous_spans(std_span)
198
+ # return std_span
199
+ #
200
+ @staticmethod
201
+ def merge_continuous_spans(spans):
202
+ new_spans = list()
203
+ for span in spans:
204
+ if isinstance(span, int):
205
+ new_spans.append((span, span))
206
+ else:
207
+ new_spans.append(span)
208
+ spans = new_spans
209
+ span_list = list()
210
+ start, end = None, None
211
+ for idx, span in enumerate(spans):
212
+ if isinstance(span, str):
213
+ if start is not None:
214
+ span_list.append((start, end))
215
+ span_list.append(span)
216
+ start, end = None, None
217
+ else:
218
+ s, e = span
219
+ if len(spans) == 1:
220
+ span_list.append(span)
221
+ break
222
+ elif idx == len(spans) - 1:
223
+ if start is None:
224
+ span_list.append(span)
225
+ else:
226
+ if end + 1 == s:
227
+ span_list.append((start, e))
228
+ else:
229
+ span_list.append((start, end))
230
+ span_list.append(span)
231
+ else:
232
+ if start is None:
233
+ start, end = s, e
234
+ else:
235
+ if end + 1 == s:
236
+ end = e
237
+ else:
238
+ span_list.append((start, end))
239
+ start, end = s, e
240
+ return tuple(span_list)
241
+ #
242
+ # @staticmethod
243
+ # def sort_non_str_spans(spans):
244
+ # if not any(isinstance(x, str) for x in spans):
245
+ # sorted_spans = sorted(spans, key=lambda x:get_start(x))
246
+ # return sorted_spans
247
+ # else:
248
+ # return spans
249
+
250
+ def has_symbols(self):
251
+ """
252
+
253
+ @return:
254
+ @rtype:
255
+ """
256
+
257
+ for span in self._spans:
258
+ if isinstance(span, str):
259
+ return True
260
+
261
+ return False
262
+ #
263
+ # def add_span_to_head(self, span):
264
+ # """
265
+ #
266
+ # @param span:
267
+ # @type span:
268
+ # @return:
269
+ # @rtype:
270
+ # """
271
+ # if isinstance(span, str):
272
+ # self._spans = list(self._spans)
273
+ # self._spans.insert(0, span)
274
+ # self._spans = tuple(self._spans)
275
+ # return
276
+ #
277
+ # if isinstance(span, int):
278
+ # span = [span, span]
279
+ # if isinstance(self._spans[0], (list, tuple)) and \
280
+ # span[1] == self._spans[0][0] - 1:
281
+ # self._spans = tuple([(span[0], self._spans[0][1])] + list(self._spans)[1:])
282
+ # else:
283
+ # x = list(self._spans)
284
+ # x.insert(0, span)
285
+ # self._spans = tuple(x)
286
+ #
287
+ # def remove_span_from_head(self, span):
288
+ # """
289
+ #
290
+ # @param span:
291
+ # @type span:
292
+ # @return:
293
+ # @rtype:
294
+ # """
295
+ # if isinstance(span, tuple):
296
+ # span_list = list(self._spans)
297
+ # for s in list(span):
298
+ # span_list.remove(s)
299
+ # self._spans = standardize_spans(span_list)
300
+ #
301
+ # def add_span_to_tail(self, span):
302
+ # """
303
+ #
304
+ # @param span:
305
+ # @type span:
306
+ # @return:
307
+ # @rtype:
308
+ # """
309
+ # if isinstance(span, str):
310
+ # self._spans = list(self._spans)
311
+ # self._spans.append(span)
312
+ # self._spans = tuple(self._spans)
313
+ # return
314
+ #
315
+ # if isinstance(span, int):
316
+ # span = [span, span]
317
+ #
318
+ # if isinstance(self._spans[-1], (list, tuple)) and \
319
+ # span[0] == self._spans[-1][1] + 1:
320
+ # self._spans = tuple(list(self._spans)[:-1] + [(self._spans[-1][0], span[1])])
321
+ # else:
322
+ # x = list(self._spans)
323
+ # x.append(span)
324
+ # self._spans = tuple(x)
325
+ #
326
+ # def add_spans_to_head(self, spans):
327
+ # """
328
+ #
329
+ # @param span:
330
+ # @type span:
331
+ # @return:
332
+ # @rtype:
333
+ # """
334
+ #
335
+ # for span in reversed(spans):
336
+ # self.add_span_to_head(span)
337
+ #
338
+ # def add_spans_to_tail(self, spans):
339
+ # """
340
+ #
341
+ # @param span:
342
+ # @type span:
343
+ # @return:
344
+ # @rtype:
345
+ # """
346
+ #
347
+ # for span in spans:
348
+ # self.add_span_to_tail(span)
349
+
350
+ @property
351
+ def spans(self):
352
+ """
353
+
354
+ @return:
355
+ @rtype:
356
+ """
357
+ return self._spans
358
+
359
+ @spans.setter
360
+ def spans(self, spans):
361
+ """
362
+
363
+ @param spans:
364
+ @type spans:
365
+ @return:
366
+ @rtype:
367
+ """
368
+ raise Exception("spans should not be set directly. please use OIAGraph.modify_node_spans")
369
+
370
+ # self._spans = standardize_spans(spans)
371
+
372
+ # def sort_spans(self):
373
+ # assert isinstance(self, OIAWordsNode)
374
+ # spans = self.spans
375
+ # spans = [x for x in spans if isinstance(x, tuple)]
376
+ # sorted_spans = sorted(spans, key=lambda x: x[0])
377
+ # return sorted_spans
378
+ #
379
+ # def merge_span(self):
380
+ # if any(isinstance(span, str) for span in self.spans):
381
+ # return self.spans
382
+ # sorted_spans = self.sort_spans()
383
+ # new_span_list = list()
384
+ # s = sorted_spans[0][0]
385
+ # e = sorted_spans[0][1]
386
+ # for span in sorted_spans[1:]:
387
+ # if span[0] == e + 1:
388
+ # e = span[1]
389
+ # else:
390
+ # new_span_list.append((s, e))
391
+ # s = span[0]
392
+ # e = span[1]
393
+ # new_span_list.append((s, e))
394
+ # self.spans = new_span_list
395
+
396
+ @property
397
+ def readable_spans(self):
398
+ """
399
+
400
+ @return:
401
+ @rtype:
402
+ """
403
+ return readable_spans(self._spans)
404
+
405
+ def __str__(self):
406
+ """
407
+
408
+ :return:
409
+ """
410
+ return ",".join(map(str, self.spans))
411
+
412
+ def __contains__(self, word_id):
413
+ """
414
+
415
+ :param word_id:
416
+ :return:
417
+ """
418
+
419
+ for span in self._spans:
420
+ if isinstance(span, str):
421
+ if span == word_id:
422
+ return True
423
+ else:
424
+ continue
425
+ else:
426
+ start, end = span
427
+ if start <= word_id <= end:
428
+ return True
429
+ return False
430
+
431
+ def words(self, with_aux=True):
432
+ """
433
+
434
+ :return:
435
+ """
436
+ for span in self._spans:
437
+ if isinstance(span, str):
438
+ if with_aux:
439
+ yield span
440
+ else:
441
+ start, end = span
442
+ for i in range(start, end + 1):
443
+ yield i
444
+
445
+ def indexes(self, with_aux=True):
446
+ """
447
+
448
+ :return:
449
+ """
450
+ for span in self._spans:
451
+ if isinstance(span, str):
452
+ pass
453
+ else:
454
+ start, end = span
455
+ for i in range(start, end + 1):
456
+ yield i
457
+
458
+
459
+ class GPGAuxNode(GPGNode):
460
+ """
461
+ GPGNode
462
+ """
463
+
464
+ def __init__(self, label=None, id=None, pos=None, confidence=None, *args, **kwargs):
465
+
466
+ super().__init__(id=id, pos=pos, confidence=confidence, *args, **kwargs)
467
+ self.label = label
468
+ self.contexts = list()
469
+
470
+ def __str__(self):
471
+ """
472
+
473
+ :return:
474
+ """
475
+ return self.label
476
+
477
+ class GPGTextNode(GPGNode):
478
+
479
+ def __init__(self, text, pos, confidence=None):
480
+ super().__init__()
481
+ self.text = text
482
+ self.pos = pos
483
+ self.confidence = confidence
484
+
485
+ def __str__(self):
486
+ """
487
+
488
+ :return:
489
+ """
490
+ return self.text
491
+
492
+
493
+
494
+ import networkx as nx
495
+
496
+
497
+ class GPGEdge(Edge):
498
+ """
499
+ a set of relations between a pair of nodes for multiple edges.
500
+ behaves like a single relation (that is, a string)
501
+ for code compatability
502
+ """
503
+
504
+ def __init__(self, label=None, mod=False, confidence=None):
505
+ super().__init__()
506
+ self.label = label
507
+ self.confidence = None
508
+ self.mod = mod
509
+ self.contexts = []
510
+ self.confidence = confidence
511
+
512
+ def __str__(self):
513
+
514
+ return self.label
515
+
516
+ def __bool__(self):
517
+ """
518
+
519
+ :return:
520
+ """
521
+ return self.label is not None
522
+
523
+ @property
524
+ def value(self):
525
+ """
526
+ :return:
527
+ :rtype:
528
+ """
529
+ return self.label
530
+
531
+ @value.setter
532
+ def value(self, value):
533
+ """
534
+ :return:
535
+ :rtype:
536
+ """
537
+ self.label = value
538
+
539
+
540
+ def _empty_hook():
541
+ """
542
+ _empty_hook
543
+ """
544
+
545
+ pass
546
+
547
+ class GraphRootMixin:
548
+
549
+ def __init__(self, *args, **kwargs):
550
+ super().__init__(*args, **kwargs)
551
+ self.root_ = None
552
+
553
+ @property
554
+ def root(self):
555
+ """
556
+ Return the root
557
+ * roots = [nodes with zero in-degree].
558
+ * if only one root found, return it, whether it is virtual or not
559
+ * else return the node with label == 'Root', that is, the virtual root
560
+ Contracts:
561
+ * if no virtual root, the program is running on the training data, and there is only one
562
+ node with zero in-degree
563
+ Returns:
564
+ """
565
+ if self.root_ is None:
566
+ topo_roots = [node for node in self.nodes()
567
+ if self.g.in_degree[node.ID] == 0]
568
+
569
+ if len(topo_roots) == 1:
570
+ self.root_ = topo_roots[0]
571
+ else:
572
+ virtual_roots = [node for node in self.nodes()
573
+ if isinstance(node, GPGAuxNode) and node.label == 'Root']
574
+ if len(virtual_roots) == 1:
575
+ self.root_ = virtual_roots[0]
576
+ else:
577
+ raise Exception("Bad Graph with multiple roots or no roots. ")
578
+
579
+ return self.root_
580
+
581
+ @root.setter
582
+ def root(self, value):
583
+ self.root_ = value
584
+
585
+ def update_root(self):
586
+ topo_roots = [node for node in self.nodes()
587
+ if self.g.in_degree[node.ID] == 0]
588
+
589
+ if len(topo_roots) == 1:
590
+ self.root_ = topo_roots[0]
591
+ else:
592
+ virtual_roots = [node for node in self.nodes()
593
+ if isinstance(node, GPGAuxNode) and node.label == 'Root']
594
+ if len(virtual_roots) == 1:
595
+ self.root_ = virtual_roots[0]
596
+ else:
597
+ raise Exception("Bad Graph with multiple roots or no roots. ")
598
+
599
+
600
+ class TextGPGraph(DirectedGraph, LearnableGraph, GraphRootMixin):
601
+
602
+ def add_node(self, node: Union[GPGTextNode, GPGAuxNode], reuse_id=False):
603
+ """
604
+ Add a node to the graph
605
+ """
606
+ assert isinstance(node, (GPGTextNode, GPGAuxNode)), type(node)
607
+ return super().add_node(node, reuse_id=reuse_id)
608
+
609
+ def add_edge(self, ni, nj, e):
610
+ """
611
+ Add an edge to the graph
612
+ """
613
+ if isinstance(e, str):
614
+ e = GPGEdge(label=e)
615
+
616
+ return super().add_edge(ni, nj, e)
617
+
618
+ def node_text(self, node, interval=" "):
619
+ """
620
+ Return the text of a node
621
+ """
622
+ if isinstance(node, GPGAuxNode):
623
+ return node.label
624
+ else:
625
+ return node.text
626
+
627
+ def add_relation(self, ni, nj, rel):
628
+ """
629
+ Add an edge to the graph
630
+ """
631
+ if isinstance(rel, str):
632
+ edge = GPGEdge(rel)
633
+ elif isinstance(rel, GPGEdge):
634
+ confidence = rel.confidence
635
+ edge = GPGEdge(rel.label, confidence=confidence)
636
+ else:
637
+ raise Exception("Unknown rel type")
638
+ return super().add_edge(ni, nj, edge)
639
+
640
+ def remove_relation(self, ni, nj):
641
+ """
642
+ Remove an edge from the graph
643
+ """
644
+ super().remove_edge_between(ni, nj)
645
+
646
+ class GPGraph(DirectedGraph, LearnableGraph, GraphRootMixin):
647
+ """
648
+ Dependency graph
649
+ """
650
+
651
+ def __init__(self, g=None):
652
+
653
+ super().__init__(g=g)
654
+
655
+ self.meta = dict()
656
+ self.words = []
657
+ self.context_hook = _empty_hook
658
+
659
+
660
+ self.spans2node = dict()
661
+
662
+ if isinstance(g, GPGraph):
663
+ self.meta = g.meta
664
+ self.words = g.words
665
+ self._root = g.root_
666
+ self.spans2node = g.spans2node
667
+
668
+ def __copy__(self):
669
+ """
670
+
671
+ :return:
672
+ """
673
+ from copy import copy
674
+ copied = DirectedGraph.__copy__(self)
675
+ copied.meta = copy(self.meta)
676
+ copied.words = copy(self.words)
677
+ copied.context_hook = self.context_hook
678
+ return copied
679
+
680
+ def __deepcopy__(self, memodict={}):
681
+ """
682
+
683
+ :param memodict:
684
+ :type memodict:
685
+ :return:
686
+ :rtype:
687
+ """
688
+
689
+ from copy import deepcopy
690
+
691
+ copied = DirectedGraph.__deepcopy__(self)
692
+ copied.meta = deepcopy(self.meta)
693
+
694
+ copied.words = deepcopy(self.words)
695
+ copied.context_hook = deepcopy(self.context_hook)
696
+ return copied
697
+
698
+
699
+
700
+ def set_words(self, words):
701
+ """
702
+
703
+ :param words:
704
+ :return:
705
+ """
706
+ if isinstance(words, list):
707
+ self.words = words
708
+ else:
709
+ raise Exception("words input not list.")
710
+ #
711
+ # def modify_node_spans(self, node, spans):
712
+ # original_spans = node.spans
713
+ # node.spans = spans
714
+ # del self.spans2node[original_spans]
715
+ # self.spans2node[node.spans] = node
716
+
717
+ def add_words(self, words, pos=None):
718
+ """
719
+
720
+ :param head:
721
+ :return:
722
+ """
723
+ #
724
+ # if len(words) == 1 and isinstance(words[0], float):
725
+ # words = tuple(words)
726
+ # if words not in self.spans2node:
727
+ # self.spans2node[words] = self.add_aux("(be)")
728
+ #
729
+ # return self.spans2node[words]
730
+ #
731
+ # if any(isinstance(x, float) for x in words):
732
+ # raise Exception("float found")
733
+
734
+ spans = positions2spans(words)
735
+
736
+ return self.add_spans(spans, pos)
737
+
738
+ def set_context_hook(self, hook):
739
+ """
740
+
741
+ :param hook:
742
+ :return:
743
+ """
744
+ self.context_hook = hook
745
+
746
+ def clear_context_hook(self):
747
+ """
748
+
749
+ :param hook:
750
+ :return:
751
+ """
752
+ self.context_hook = _empty_hook
753
+
754
+ def add_node(self, node, reuse_id=False):
755
+ """
756
+
757
+ :param node:
758
+ :return:
759
+ """
760
+ assert isinstance(node, GPGPhraseNode) or isinstance(node, GPGAuxNode), f"Invalid node type: {type(node)}"
761
+
762
+ context = self.context_hook()
763
+ if context:
764
+ node.contexts.extend(context)
765
+
766
+ if isinstance(node, GPGPhraseNode):
767
+ node._spans = standardize_spans(node.spans)
768
+
769
+ if node.spans in self.spans2node:
770
+ raise Exception("Repeated node found: {}".format(node.spans))
771
+ self.spans2node[node.spans] = super().add_node(node, reuse_id=reuse_id)
772
+ return self.spans2node[node.spans]
773
+ else:
774
+ node = super().add_node(node, reuse_id=reuse_id)
775
+ return node
776
+
777
+ def modify_node_spans(self, node, spans):
778
+ """
779
+ Modify the spans of a node
780
+ """
781
+ assert node.spans in self.spans2node, f"Node spans {node.spans} not found in spans2node: {self.spans2node}"
782
+ if self.spans2node[node.spans] == node:
783
+ del self.spans2node[node.spans]
784
+ node._spans = standardize_spans(spans)
785
+ self.spans2node[node.spans] = node
786
+
787
+
788
+ #
789
+ # def add_repeated_node(self, node, reuse_id=False):
790
+ # """
791
+ #
792
+ # :param node:
793
+ # :return:
794
+ # """
795
+ # assert isinstance(node, OIAWordsNode) or isinstance(node, OIAAuxNode)
796
+ #
797
+ # context = self.context_hook()
798
+ # if context:
799
+ # node.contexts.extend(context)
800
+ #
801
+ # if isinstance(node, OIAWordsNode):
802
+ # node._spans = standardize_spans(node.spans)
803
+ #
804
+ # if node.spans in self.spans2node:
805
+ # raise Exception("Repeated node found: {}".format(node.spans))
806
+ # self.spans2node[node.spans] = super().add_node(node, reuse_id=reuse_id)
807
+ # return self.spans2node[node.spans]
808
+ # else:
809
+ # node = super().add_node(node, reuse_id=reuse_id)
810
+ # return node
811
+
812
+ def remove_node(self, node):
813
+ if isinstance(node, GPGPhraseNode):
814
+ # node.spans = standardize_spans(node.spans)
815
+ if node.spans in self.spans2node:
816
+ del self.spans2node[node.spans]
817
+ node = super().remove_node(node)
818
+ return node
819
+
820
+ def add_spans(self, spans, pos=None):
821
+ """
822
+
823
+ :param node:
824
+ :return:
825
+ """
826
+
827
+ spans = standardize_spans(spans)
828
+
829
+ if spans not in self.spans2node:
830
+ added_node = GPGPhraseNode(spans)
831
+ added_node.pos = pos
832
+ self.spans2node[spans] = super().add_node(added_node)
833
+
834
+ return self.spans2node[spans]
835
+
836
+ def has_node(self, node: GPGNode):
837
+ """
838
+
839
+ @param node:
840
+ @type node:
841
+ @return:
842
+ @rtype:
843
+ """
844
+ if self.g.has_node(node.ID):
845
+ return True
846
+ else:
847
+ return False
848
+
849
+ def has_word(self, words):
850
+ """
851
+
852
+ :param word:
853
+ :return:
854
+ """
855
+ spans = positions2spans(words)
856
+ for node in self.nodes():
857
+ if isinstance(node, GPGPhraseNode) and node.spans == spans:
858
+ added_node = node
859
+ return True
860
+ return False
861
+
862
+ def get_node_by_words(self, positions):
863
+ """
864
+
865
+ @param positions:
866
+ @type positions:
867
+ @return:
868
+ @rtype:
869
+ """
870
+ spans = positions2spans(positions)
871
+
872
+ spans = standardize_spans(spans)
873
+
874
+ if spans in self.spans2node:
875
+ return self.spans2node[spans]
876
+
877
+ return None
878
+
879
+ def get_node_by_spans(self, spans):
880
+ spans = standardize_spans(spans)
881
+ if spans in self.spans2node:
882
+ return self.spans2node[spans]
883
+ return None
884
+
885
+ def has_relation(self, node1: GPGNode,
886
+ node2: GPGNode,
887
+ direct_link=True):
888
+ """
889
+
890
+ :return:
891
+ @param node1:
892
+ @type node1:
893
+ @param node2:
894
+ @type node2:
895
+ """
896
+
897
+ if node1 is None or node2 is None:
898
+ return False
899
+
900
+ if direct_link and (self.g.has_edge(node1.ID, node2.ID) or self.g.has_edge(node2.ID, node1.ID)):
901
+ return True
902
+ elif not direct_link and (
903
+ nx.algorithms.shortest_paths.generic.has_path(self.g, node1.ID, node2.ID) or
904
+ nx.algorithms.shortest_paths.generic.has_path(self.g, node2.ID, node1.ID)):
905
+ return True
906
+
907
+ return False
908
+
909
+ def add_aux(self, label, pos=None):
910
+ """
911
+
912
+ :param label:
913
+ :return:
914
+ """
915
+
916
+ node = GPGAuxNode(label)
917
+ node.pos = pos
918
+ self.add_node(node)
919
+
920
+ return node
921
+
922
+ def get_aux(self, label):
923
+ """
924
+
925
+ :param label:
926
+ :return:
927
+ """
928
+ for node_id in self.g.nodes:
929
+ node = self.get_node(node_id)
930
+ if isinstance(node, GPGAuxNode) and node.label == label:
931
+ yield node
932
+
933
+ def get_edge(self, node1, node2):
934
+ """
935
+
936
+ :param node1:
937
+ :param node2:
938
+ :return:
939
+ """
940
+ try:
941
+ return super().get_edge(node1, node2)
942
+ except:
943
+ return None
944
+
945
+ def spans(self):
946
+ """
947
+
948
+ @return:
949
+ @rtype:
950
+ """
951
+
952
+ spans = []
953
+
954
+ for x in self.nodes():
955
+ if isinstance(x, GPGPhraseNode):
956
+ for span in x.spans:
957
+ if isinstance(span, str):
958
+ continue
959
+ elif isinstance(span, int):
960
+ span = (span, span)
961
+ spans.append(span)
962
+ else:
963
+ spans.append(tuple(span))
964
+
965
+ spans.sort(key=lambda x: x[0])
966
+
967
+ return spans
968
+
969
+ def parents_on_path(self, node, ancestor):
970
+ """
971
+
972
+ :param node:
973
+ :param ancestor:
974
+ :return:
975
+ """
976
+ for path in nx.all_simple_paths(self.g, ancestor.ID, node.ID):
977
+ yield self.get_node(path[-2])
978
+
979
+ def paths(self, node1, node2):
980
+ """
981
+
982
+ :param node1:
983
+ :param node2:
984
+ :return:
985
+ """
986
+ for path in nx.all_simple_paths(self.g, node1.ID, node2.ID):
987
+ yield [self.get_node(x) for x in path]
988
+
989
+ def replace(self, old_node, new_node):
990
+ """
991
+
992
+ :param old_node:
993
+ :param new_node:
994
+ :return:
995
+ """
996
+
997
+ if new_node.ID == old_node.ID:
998
+ raise Exception("Bad business logic: cannot replace a node with itself")
999
+
1000
+ # if self.g.has_node(new_node.ID):
1001
+ # raise Exception("Bad business logic: the new node is already in the graph")
1002
+
1003
+ if not self.has_node(new_node):
1004
+ self.add_node(new_node)
1005
+
1006
+ for child, rel in self.children(old_node):
1007
+ self.g.add_edge(new_node.ID, child.ID, Edge=rel)
1008
+
1009
+ for parent, rel in self.parents(old_node):
1010
+ self.g.add_edge(parent.ID, new_node.ID, Edge=rel)
1011
+
1012
+ self.remove_node(old_node)
1013
+
1014
+ def add_edge(self, start_node, end_node, edge):
1015
+ """
1016
+
1017
+ @param start_node:
1018
+ @type start_node:
1019
+ @param end_node:
1020
+ @type end_node:
1021
+ @param edge:
1022
+ @type edge:
1023
+ @return:
1024
+ @rtype:
1025
+ """
1026
+ context = self.context_hook()
1027
+ if context:
1028
+ edge.contexts.extend(context)
1029
+
1030
+ if start_node.ID not in self.g.nodes():
1031
+ raise ValueError('start node not in graph')
1032
+ if end_node.ID not in self.g.nodes():
1033
+ raise ValueError('end node not in graph')
1034
+
1035
+ if isinstance(edge, str):
1036
+ edge = GPGEdge(label=edge)
1037
+
1038
+ # self.add_node(start_node, reuse_id=True)
1039
+ # self.add_node(end_node, reuse_id=True)
1040
+ edge.start = start_node.ID
1041
+ edge.end = end_node.ID
1042
+ self.g.add_edge(start_node.ID, end_node.ID, Edge=edge)
1043
+
1044
+ # def add_argument(self, pred_node, arg_node, index, mod=False):
1045
+ # """
1046
+
1047
+ # :param node1:
1048
+ # :param node2:
1049
+ # :param rel:
1050
+ # :return:
1051
+ # """
1052
+
1053
+ # # if isinstance(pred_node.ID, int) or isinstance(pred_node.ID, str):
1054
+ # # raise Exception("Bad ID")
1055
+ # # if isinstance(arg_node.ID, int) or isinstance(arg_node.ID, str):
1056
+ # # raise Exception("Bad ID")
1057
+
1058
+ # if mod:
1059
+
1060
+ # if any(self.node_text(arg_node).lower().startswith(x)
1061
+ # for x in {"what ", "which ", "where ", "who ",
1062
+ # "whom ", "when ", "why ", "how "}):
1063
+ # edge_label = "func.arg"
1064
+ # else:
1065
+ # edge_label = "as:pred.arg.{0}".format(index)
1066
+
1067
+ # edge = GPGEdge(label=edge_label, mod=mod)
1068
+
1069
+ # self.add_edge(arg_node, pred_node, edge)
1070
+ # else:
1071
+
1072
+ # edge_label = "pred.arg.{0}".format(index)
1073
+
1074
+ # edge = GPGEdge(label=edge_label, mod=mod)
1075
+ # self.add_edge(pred_node, arg_node, edge)
1076
+
1077
+ # def add_mod(self, modifier, center):
1078
+ # """
1079
+
1080
+ # :param target:
1081
+ # :param source:
1082
+ # :return:
1083
+ # """
1084
+
1085
+ # edge = GPGEdge(label="modification", mod=False)
1086
+
1087
+ # self.add_edge(center, modifier, edge)
1088
+
1089
+ # def add_function(self, functor, argument, index=None):
1090
+ # """
1091
+
1092
+ # :param functor:
1093
+ # :param argument:
1094
+ # :return:
1095
+ # """
1096
+ # if index is None:
1097
+ # index = "1"
1098
+ # edge_label = "func.arg" #.format(index)
1099
+
1100
+ # # if isinstance(functor.ID, int) or isinstance(functor.ID, str):
1101
+ # # raise Exception("Bad ID")
1102
+ # # if isinstance(argument.ID, int) or isinstance(argument.ID, str):
1103
+ # # raise Exception("Bad ID")
1104
+
1105
+ # edge = GPGEdge(label=edge_label, mod=False)
1106
+
1107
+ # functor.is_func = True
1108
+
1109
+ # self.add_edge(functor, argument, edge)
1110
+
1111
+ # def add_ref(self, source, ref):
1112
+ # """
1113
+
1114
+ # :param target:
1115
+ # :param source:
1116
+ # :return:
1117
+ # """
1118
+
1119
+ # edge = GPGEdge(label="ref", mod=False)
1120
+
1121
+ # self.add_edge(source, ref, edge)
1122
+
1123
+ def add_relation(self, node1, node2, rel, confidence=None):
1124
+ """
1125
+
1126
+ :param node1:
1127
+ :param node2:
1128
+ :param rel:
1129
+ :return:
1130
+ """
1131
+ if isinstance(rel, str):
1132
+ edge = GPGEdge(rel, confidence=confidence)
1133
+ elif isinstance(rel, GPGEdge):
1134
+ if confidence is None:
1135
+ confidence = rel.confidence
1136
+ edge = GPGEdge(rel.label, confidence=confidence)
1137
+ else:
1138
+ raise Exception("Unknown rel type")
1139
+ self.add_edge(node1, node2, edge)
1140
+
1141
+ def merge_continuous_spans(self):
1142
+ nodes = list(self.nodes())
1143
+ for node in nodes:
1144
+ if isinstance(node, GPGAuxNode):
1145
+ continue
1146
+
1147
+ spans = node.spans
1148
+ span_tuple = GPGPhraseNode.merge_continuous_spans(spans)
1149
+ # print('old', spans)
1150
+ # print('new', span_tuple)
1151
+ #del self.spans2node[node.spans]
1152
+ self.modify_node_spans(node, span_tuple)
1153
+
1154
+ #node.spans = span_list
1155
+ #self.spans2node[node.spans] = node
1156
+
1157
+ def remove_relation(self, node1, node2):
1158
+ """
1159
+
1160
+ :param node1:
1161
+ :param node2:
1162
+ :return:
1163
+ """
1164
+ super().remove_edge_between(node1, node2)
1165
+
1166
+ def relations(self):
1167
+ """
1168
+
1169
+ :return:
1170
+ """
1171
+ return super().edges()
1172
+
1173
+ def node_text(self, node, interval=" "):
1174
+ """
1175
+
1176
+ @param node:
1177
+ @type node:
1178
+ @return:
1179
+ @rtype:
1180
+ """
1181
+
1182
+ if isinstance(node, GPGPhraseNode):
1183
+ node_texts = []
1184
+ for span in node.spans:
1185
+ if isinstance(span, str):
1186
+ node_texts.append(span)
1187
+ elif isinstance(span, tuple) and isinstance(span[0], str):
1188
+ node_texts.append(span[0])
1189
+ else:
1190
+ start, end = span
1191
+ for i in range(start, end + 1):
1192
+ node_texts.append(self.words[i])
1193
+
1194
+ node_text = interval.join(node_texts)
1195
+ else:
1196
+ node_text = node.label
1197
+
1198
+ return node_text
1199
+
1200
+ def topological_sort(self):
1201
+ """
1202
+
1203
+ :return:
1204
+ """
1205
+
1206
+ for id in nx.topological_sort(self.g):
1207
+ yield self.get_node(id)
1208
+
1209
+ @staticmethod
1210
+ def parse(json_obj):
1211
+ """
1212
+ Parse a JSON object into an OIAGraph.
1213
+
1214
+ :param json_obj: JSON object representing the graph
1215
+ :param check_valid: Whether to validate the graph after parsing
1216
+ :return: OIAGraph instance
1217
+ """
1218
+ if isinstance(json_obj, str):
1219
+ json_obj = json.loads(json_obj)
1220
+
1221
+ assert isinstance(json_obj, dict)
1222
+
1223
+ graph = GPGraph()
1224
+ graph.meta = json_obj["meta"]
1225
+ graph.words = [0] * len(json_obj["words"])
1226
+ if isinstance(json_obj["words"][0], list):
1227
+ for id, word in json_obj["words"]:
1228
+ graph.words[id] = word
1229
+ elif isinstance(json_obj["words"][0], str):
1230
+ for id, word in enumerate(json_obj["words"]):
1231
+ graph.words[id] = word
1232
+ else:
1233
+ raise TypeError("Invalid word format")
1234
+
1235
+ if len(json_obj["oia"]["nodes"]) == 0:
1236
+ return graph
1237
+
1238
+ nodes = dict()
1239
+
1240
+ for node_info in json_obj["oia"]["nodes"]:
1241
+ if isinstance(node_info, list):
1242
+ id, spans, pos = node_info[:3]
1243
+ confidence = node_info[3] if len(node_info) > 3 else None
1244
+ elif isinstance(node_info, dict):
1245
+ spans = node_info['spans']
1246
+ pos = node_info['type']
1247
+ id = len(nodes)
1248
+ confidence = node_info.get('confidence')
1249
+ else:
1250
+ raise TypeError("Invalid node format")
1251
+
1252
+ if isinstance(spans, str) or (isinstance(spans, (list, tuple)) and len(spans) == 1 and isinstance(spans[0], str)):
1253
+ aux_node = GPGAuxNode(spans[0] if isinstance(spans, (list, tuple)) else spans)
1254
+ aux_node.ID = id
1255
+ node = graph.add_node(aux_node, reuse_id=True)
1256
+ # elif all(span in ArgPlaceholders for span in spans):
1257
+ # aux_node = OIAAuxNode('Parataxis')
1258
+ # aux_node.ID = id
1259
+ # node = graph.add_node(aux_node, reuse_id=True)
1260
+ else:
1261
+ node = GPGPhraseNode(spans)
1262
+ node.ID = id
1263
+ graph.add_node(node, reuse_id=True)
1264
+
1265
+ node.pos = pos
1266
+ node.confidence = confidence
1267
+ nodes[id] = node
1268
+
1269
+ graph.node_id_base = max([node.ID for node in graph.nodes()]) + 1
1270
+
1271
+ for edge_info in json_obj["oia"]["edges"]:
1272
+ if isinstance(edge_info, list):
1273
+ n1_id, edge_label, n2_id = edge_info[:3]
1274
+ confidence = edge_info[3] if len(edge_info) > 3 else None
1275
+ elif isinstance(edge_info, dict):
1276
+ n1_id = edge_info['start']
1277
+ n2_id = edge_info['end']
1278
+ edge_label = edge_info['label']
1279
+ confidence = edge_info.get('confidence')
1280
+ else:
1281
+ raise TypeError("Invalid edge format")
1282
+
1283
+ node1 = nodes[n1_id]
1284
+ node2 = nodes[n2_id]
1285
+ graph.add_relation(node1, node2, edge_label, confidence)
1286
+
1287
+ return graph
1288
+
1289
+ # @staticmethod
1290
+ # def validate(graph):
1291
+ # """
1292
+ # Validate the OIAGraph structure.
1293
+ # Raises an exception if the graph is invalid.
1294
+ # """
1295
+ # for node in graph.nodes():
1296
+ # if isinstance(node, OIAAuxNode):
1297
+ # if node.label[0] not in ExtraNodeToken:
1298
+ # raise Exception(f"Invalid auxiliary node {node.label}")
1299
+ # elif isinstance(node, OIAWordsNode):
1300
+ # for span in node.spans:
1301
+ # if isinstance(span, str) and span not in ExtraNodeToken:
1302
+ # raise Exception(f"Invalid node span {span}")
1303
+
1304
+ # if node.pos is not None and node.pos not in NodePoses:
1305
+ # raise Exception(f"Invalid node type {node.pos}")
1306
+
1307
+ # for _, edge, _ in graph.relations():
1308
+ # if edge.label not in Edges:
1309
+ # raise Exception(f"Invalid edge {edge.label}")
1310
+
1311
+ # @staticmethod
1312
+ # def validate(graph):
1313
+ # """
1314
+ # Validate the OIAGraph structure.
1315
+ # Raises an exception if the graph is invalid.
1316
+ # """
1317
+ # for node in graph.nodes():
1318
+ # if isinstance(node, OIAAuxNode):
1319
+ # if node.label[0] not in ExtraNodeToken:
1320
+ # raise Exception(f"Invalid auxiliary node {node.label}")
1321
+ # elif isinstance(node, OIAWordsNode):
1322
+ # for span in node.spans:
1323
+ # if isinstance(span, str) and span not in ExtraNodeToken:
1324
+ # raise Exception(f"Invalid node span {span}")
1325
+
1326
+ # if node.pos is not None and node.pos not in NodePoses:
1327
+ # raise Exception(f"Invalid node type {node.pos}")
1328
+
1329
+ # for _, edge, _ in graph.relations():
1330
+ # if edge.label not in Edges:
1331
+ # raise Exception(f"Invalid edge {edge.label}")
1332
+
1333
+ def data_for_label(self):
1334
+ """
1335
+
1336
+ @return:
1337
+ @rtype:
1338
+ """
1339
+
1340
+ oia = dict()
1341
+
1342
+ oia["nodes"] = []
1343
+ node2idx = dict()
1344
+ for idx, node in enumerate(self.nodes()):
1345
+ node2idx[node.ID] = idx
1346
+ # oia["nodes"].append((idx, node.spans, node.pos))
1347
+ if isinstance(node, GPGPhraseNode):
1348
+ oia["nodes"].append((idx, node.spans, node.pos, node.confidence))
1349
+ else:
1350
+ oia["nodes"].append((idx, node.label, node.pos, node.confidence))
1351
+
1352
+ oia["edges"] = []
1353
+ for idx, (n1, edge, n2) in enumerate(self.relations()):
1354
+ n1_id = node2idx[n1.ID]
1355
+ n2_id = node2idx[n2.ID]
1356
+ oia["edges"].append((n1_id, edge.label, n2_id, edge.confidence))
1357
+
1358
+ data = dict()
1359
+ data["meta"] = self.meta
1360
+ data['words'] = [(idx, word) for idx, word in enumerate(self.words)]
1361
+ data['oia'] = oia
1362
+
1363
+ return data
1364
+
1365
+ def data(self):
1366
+ """
1367
+
1368
+ @return:
1369
+ @rtype:
1370
+ """
1371
+
1372
+ oia = dict()
1373
+
1374
+ oia["nodes"] = []
1375
+ node2idx = dict()
1376
+ for idx, node in enumerate(self.nodes()):
1377
+ node2idx[node.ID] = idx
1378
+ # oia["nodes"].append((idx, node.spans, node.pos))
1379
+ if isinstance(node, GPGPhraseNode):
1380
+ if node.confidence is None:
1381
+ oia["nodes"].append({'spans': node.spans, 'type': node.pos})
1382
+ else:
1383
+ oia["nodes"].append({'spans': node.spans, 'type': node.pos, 'confidence': node.confidence})
1384
+ else:
1385
+ if node.confidence is None:
1386
+ oia["nodes"].append({'spans': node.label, 'type': node.pos})
1387
+ else:
1388
+ oia["nodes"].append({'spans': node.label, 'type': node.pos, 'confidence': node.confidence})
1389
+
1390
+ oia["edges"] = []
1391
+ for idx, (n1, edge, n2) in enumerate(self.relations()):
1392
+ n1_id = node2idx[n1.ID]
1393
+ n2_id = node2idx[n2.ID]
1394
+ if edge.confidence is None:
1395
+ oia["edges"].append({'start': n1_id, 'end': n2_id, 'label': edge.label})
1396
+ else:
1397
+ oia["edges"].append({'start': n1_id, 'end': n2_id, 'label': edge.label, 'confidence': edge.confidence})
1398
+
1399
+ data = dict()
1400
+ data["meta"] = self.meta
1401
+ data['words'] = self.words
1402
+ data['oia'] = oia
1403
+
1404
+ return data
1405
+
1406
+ def readable(self):
1407
+ """
1408
+
1409
+ @return:
1410
+ @rtype:
1411
+ """
1412
+
1413
+ oia = dict()
1414
+
1415
+ oia["nodes"] = []
1416
+ node2idx = dict()
1417
+ for idx, node in enumerate(self.nodes()):
1418
+ node2idx[node.ID] = idx
1419
+ # oia["nodes"].append((idx, node.spans, node.pos))
1420
+ if isinstance(node, GPGPhraseNode):
1421
+ if not hasattr(node, 'concept'):
1422
+ oia["nodes"].append({'nid': node2idx[node.ID], 'spans': sent_spans2list(node.spans),
1423
+ 'type': node.pos, 'text': self.node_text(node, interval='')})
1424
+ else:
1425
+ oia["nodes"].append({'nid': node2idx[node.ID], 'spans': sent_spans2list(node.spans),
1426
+ 'type': node.pos, 'text': self.node_text(node, interval=''), 'concept': node.concept})
1427
+ else:
1428
+ if not hasattr(node, 'concept'):
1429
+ oia["nodes"].append({'nid': node2idx[node.ID], 'spans': node.label, 'type': node.pos,
1430
+ 'text': self.node_text(node, interval='')})
1431
+ else:
1432
+ oia["nodes"].append({'nid': node2idx[node.ID], 'spans': node.label, 'type': node.pos,
1433
+ 'text': self.node_text(node, interval=''), 'concept': node.concept})
1434
+
1435
+ oia["edges"] = []
1436
+ for idx, (n1, edge, n2) in enumerate(self.relations()):
1437
+ n1_id = node2idx[n1.ID]
1438
+ n2_id = node2idx[n2.ID]
1439
+ if edge.confidence is None:
1440
+ oia["edges"].append({'start': n1_id, 'end': n2_id, 'label': edge.label})
1441
+ else:
1442
+ oia["edges"].append({'start': n1_id, 'end': n2_id, 'label': edge.label, 'confidence': edge.confidence})
1443
+
1444
+ data = dict()
1445
+ data["meta"] = self.meta
1446
+ data['words'] = self.words
1447
+ data['oia'] = oia
1448
+
1449
+ return data
1450
+
1451
+ # @staticmethod
1452
+ # def parse_readable(yaml_obj, check_valid=True):
1453
+ # """
1454
+
1455
+ # :param oia_graph:
1456
+ # :return:
1457
+ # """
1458
+ # if isinstance(yaml_obj, str):
1459
+ # yaml_obj = json.loads(yaml_obj)
1460
+
1461
+ # assert isinstance(yaml_obj, dict)
1462
+
1463
+ # graph = OIAGraph()
1464
+ # graph.meta = yaml_obj["meta"]
1465
+ # graph.words = yaml_obj['words']
1466
+
1467
+ # for node_info in yaml_obj["oia"]["nodes"]:
1468
+ # spans = node_info['spans']
1469
+ # if isinstance(spans, str):
1470
+ # if check_valid:
1471
+ # if spans not in ExtraNodeToken:
1472
+ # raise Exception("Invalid node {0} ".format(spans))
1473
+ # aux_node = OIAAuxNode(spans)
1474
+ # aux_node.ID = node_info['nid']
1475
+ # aux_node.pos = node_info['type']
1476
+ # if 'concept' in node_info:
1477
+ # aux_node.concept = node_info['concept']
1478
+ # node = graph.add_node(aux_node, reuse_id=True)
1479
+ # else:
1480
+ # node_spans = list()
1481
+ # for span in spans:
1482
+ # if 'label' in span:
1483
+ # node_spans.append(span['label'])
1484
+ # else:
1485
+ # assert 'start' in span and 'end' in span
1486
+ # node_spans.append((span['start'], span['end']))
1487
+ # for span in node_spans:
1488
+ # if check_valid:
1489
+ # if isinstance(span, str) and span not in ExtraNodeToken:
1490
+ # raise Exception("Invalid node {0} ".format(span))
1491
+
1492
+ # node = OIAWordsNode(node_spans)
1493
+ # node.ID = node_info['nid']
1494
+ # node.pos = node_info['type']
1495
+ # if 'concept' in node_info:
1496
+ # node.concept = node_info['concept']
1497
+ # graph.add_node(node, reuse_id=True)
1498
+
1499
+
1500
+ # for edge_info in yaml_obj["oia"]["edges"]:
1501
+ # edge_label = edge_info['label']
1502
+ # if check_valid:
1503
+ # if edge_label not in Edges:
1504
+ # raise Exception("Invalid edge {0} ".format(edge_label))
1505
+ # start = graph.get_node(edge_info['start'])
1506
+ # end = graph.get_node(edge_info['end'])
1507
+ # graph.add_relation(start, end, edge_label)
1508
+
1509
+ # return graph
1510
+
1511
+ def save(self, output_file_path):
1512
+ """
1513
+
1514
+ :param output_file_path:
1515
+ :return:
1516
+ """
1517
+
1518
+ data = self.data()
1519
+
1520
+ with open(output_file_path, "w", encoding="UTF8") as output_file:
1521
+ json.dump(data, output_file, cls=CompactJSONEncoder, ensure_ascii=False)
1522
+
1523
+
1524
+
1525
+ class GPGraphVisualizer(GraphVisualizer):
1526
+ """
1527
+ GPGraphVisualizer
1528
+ """
1529
+
1530
+ def __init__(self, debug=False):
1531
+
1532
+ self.debug = debug
1533
+
1534
+ def escape(self, node_text):
1535
+ """
1536
+
1537
+ @param node_text:
1538
+ @return:
1539
+ """
1540
+ special_tokens = '{}<>"'
1541
+
1542
+ for token in special_tokens:
1543
+ node_text = node_text.replace(token, "\\" + token)
1544
+
1545
+ return node_text
1546
+
1547
+ def node_label(self, graph, node, no_text=False, *args, **kwargs):
1548
+ """
1549
+
1550
+ :param node:
1551
+ :param dep_graph:
1552
+ :return:
1553
+ """
1554
+ components = []
1555
+ components.append(str(node.ID))
1556
+ if no_text:
1557
+ node_text = ""
1558
+ else:
1559
+ node_text = self.escape(graph.node_text(node))
1560
+ components.append(node_text)
1561
+
1562
+ if isinstance(node, GPGPhraseNode):
1563
+ span_str = self.escape(str(tuple(node.readable_spans)))
1564
+ components.append(span_str)
1565
+
1566
+ x = node.pos
1567
+ if x is None:
1568
+ x = 'None'
1569
+ components.append(x)
1570
+
1571
+ if hasattr(node, 'concept'):
1572
+ components.append(node.concept)
1573
+
1574
+ label = "{0}".format(" | ".join(components))
1575
+
1576
+ if self.debug and node.contexts:
1577
+ label = "{{{0}}}".format(" | ".join([label, "\n".join(node.contexts)]))
1578
+
1579
+ return label
1580
+
1581
+ def node_style(self, graph, node, *args, **kwargs):
1582
+ """
1583
+
1584
+ @param node:
1585
+ @return:
1586
+
1587
+ """
1588
+ style = {}
1589
+
1590
+ style['shape'] = "record"
1591
+ style['fillcolor'] = "grey"
1592
+ style['style'] = "filled"
1593
+
1594
+ return style
1595
+
1596
+ def edge_label(self, graph, edge, *args, **kwargs):
1597
+ """
1598
+
1599
+ @param edge:
1600
+ @param debug:
1601
+ @return:
1602
+ """
1603
+
1604
+ edge_label = edge.label
1605
+
1606
+ if self.debug and edge.contexts:
1607
+ edge_label = "{{{0}}}".format("|".join([edge_label, "\n".join(edge.contexts)]))
1608
+
1609
+ return edge_label
1610
+
1611
+ def edge_style(self, graph, edge, *args, **kwargs):
1612
+ """
1613
+
1614
+ @param node:
1615
+ @return:
1616
+
1617
+ """
1618
+ style = {}
1619
+
1620
+ return style
1621
+
1622
+
1623
+
1624
+ from typing import List
1625
+ import string
1626
+
1627
+
1628
+ def get_word_positions(sentence: str, words: List[str]) -> List[tuple]:
1629
+ """
1630
+ Get the starting and ending character positions for each word in the sentence.
1631
+
1632
+ Args:
1633
+ sentence (str): The original sentence.
1634
+ words (List[str]): The list of words in the sentence.
1635
+
1636
+ Returns:
1637
+ List[tuple]: A list of tuples where each tuple contains the starting and ending positions of a word.
1638
+ """
1639
+ positions = []
1640
+ current_pos = 0
1641
+
1642
+ for word in words:
1643
+ start_pos = sentence.find(word, current_pos)
1644
+ if start_pos == -1:
1645
+ raise ValueError(f"Word '{word}' in [{words}]not found in the sentence [{sentence}] starting from position {current_pos}.")
1646
+ end_pos = start_pos + len(word)
1647
+ positions.append((start_pos, end_pos))
1648
+ current_pos = end_pos
1649
+
1650
+ return positions
1651
+
1652
+
1653
+ def get_node_text(node: GPGPhraseNode, sentence: str, word_positions: List[tuple]):
1654
+
1655
+ word_indexes = list(node.words(with_aux=True))
1656
+
1657
+ node_label = ""
1658
+ for w in word_indexes:
1659
+ if isinstance(w, int):
1660
+ word_pos = word_positions[w]
1661
+ word_text = sentence[word_pos[0]: word_pos[1]]
1662
+ if word_pos[0] > 0 and sentence[word_pos[0] - 1] in string.whitespace:
1663
+ word_text = " " + word_text
1664
+ node_label += word_text
1665
+ else:
1666
+ node_label += w # should add space ? += (" " + " ")?
1667
+ return node_label
1668
+
1669
+
1670
+ class GraphValidator(object):
1671
+
1672
+ @property
1673
+ def name(self):
1674
+ return None
1675
+
1676
+ """
1677
+ check whether the graph is valid, and return the severity of the error, and details of the error
1678
+ The severity of the error:
1679
+ * is an float between 0 and 1. The larger the value, the more severe the error.
1680
+ * 0 means the graph is perfect in the aspect of the check
1681
+ """
1682
+ def validate(self, graph: GPGraph):
1683
+ pass
lingua/structure/utils.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ utilities for graph manipulation and visualization
3
+ """
4
+
5
+
6
+ import json
7
+ from typing import Union
8
+
9
+ from enum import Enum, auto
10
+
11
+
12
+ class AutoNamedEnum(Enum):
13
+ def _generate_next_value_(name, start, count, last_values):
14
+ return name
15
+
16
+
17
+ class CompactJSONEncoder(json.JSONEncoder):
18
+ """A JSON Encoder that puts small containers on single lines."""
19
+
20
+ CONTAINER_TYPES = (list, tuple, dict)
21
+ """Container datatypes include primitives or other containers."""
22
+
23
+ MAX_WIDTH = 70
24
+ """Maximum width of a container that might be put on a single line."""
25
+
26
+ MAX_ITEMS = 3
27
+ """Maximum number of items in container that might be put on single line."""
28
+
29
+ INDENTATION_CHAR = " "
30
+
31
+ def __init__(self, *args, **kwargs):
32
+ super().__init__(*args, **kwargs)
33
+ self.indentation_level = 0
34
+
35
+ if self.indent is None:
36
+ self.indent = 2
37
+
38
+ self.list_nest_level = 0
39
+ self.kwargs = kwargs
40
+
41
+ def encode(self, o):
42
+ """Encode JSON object *o* with respect to single line lists."""
43
+ if isinstance(o, (list, tuple)):
44
+ if self._put_on_single_line(o):
45
+ return "[" + ", ".join(self.encode(el) for el in o) + "]"
46
+ else:
47
+ self.indentation_level += 1
48
+ self.list_nest_level += 1
49
+ output = [self.indent_str + self.encode(el) for el in o]
50
+ self.indentation_level -= 1
51
+ self.list_nest_level -= 1
52
+ return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
53
+ elif isinstance(o, dict):
54
+ if o:
55
+ if self._put_on_single_line(o):
56
+ return "{ " + ", ".join(f"{self.encode(k)}: {self.encode(el)}" for k, el in o.items()) + " }"
57
+ else:
58
+ self.indentation_level += 1
59
+ output = [self.indent_str + f"{json.dumps(k)}: {self.encode(v)}" for k, v in o.items()]
60
+ self.indentation_level -= 1
61
+ return "{\n" + ",\n".join(output) + "\n" + self.indent_str + "}"
62
+ else:
63
+ return "{}"
64
+ elif isinstance(o, float): # Use scientific notation for floats, where appropiate
65
+ return format(o, "g")
66
+ # elif isinstance(o, str): # escape newlines
67
+ # o = o.replace("\n", "\\n")
68
+ # return f'"{o}"'
69
+ else:
70
+ return json.dumps(o, **self.kwargs)
71
+
72
+ def _put_on_single_line(self, o):
73
+ return self._primitives_only(o) and len(o) <= self.MAX_ITEMS and len(str(o)) - 2 <= self.MAX_WIDTH
74
+
75
+ def _primitives_only(self, o: Union[list, tuple, dict]):
76
+ if self.list_nest_level >= 1:
77
+ return True
78
+ if isinstance(o, (list, tuple)):
79
+ return not any(isinstance(el, self.CONTAINER_TYPES) for el in o)
80
+ elif isinstance(o, dict):
81
+ return not any(isinstance(el, self.CONTAINER_TYPES) for el in o.values())
82
+
83
+ @property
84
+ def indent_str(self) -> str:
85
+ return self.INDENTATION_CHAR*(self.indentation_level*self.indent)
86
+
87
+
88
+ def positions2spans(words):
89
+ """
90
+ check
91
+ """
92
+
93
+ if isinstance(words, int):
94
+ words = tuple([words])
95
+ elif isinstance(words, (list, tuple)):
96
+ words = tuple(words)
97
+ else:
98
+ raise Exception("the words must be an int or a list of int/str")
99
+
100
+ spans = []
101
+ idx = 0
102
+ while idx < len(words):
103
+ if isinstance(words[idx], str):
104
+ spans.append(words[idx])
105
+ idx += 1
106
+ else:
107
+ start_idx = idx
108
+ while start_idx + 1 < len(words) \
109
+ and (words[start_idx + 1] == words[start_idx] + 1 \
110
+ or words[start_idx + 1] == words[start_idx]):
111
+ start_idx += 1
112
+
113
+ spans.append((words[idx], words[start_idx]))
114
+ idx = start_idx + 1
115
+
116
+ return tuple(spans)
lingua/utils/__init__.py ADDED
File without changes
lingua/utils/topology_sorter.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lingua.structure.gpgraph import GPGraph, GPGNode, GPGEdge, GPGPhraseNode, GPGAuxNode
2
+ from lingua.concept.standard import LinguaGraphEdges
3
+
4
+ from typing import List, Tuple
5
+ from collections import deque
6
+
7
+
8
+ class LinguaGraphTopologySorter:
9
+
10
+ """
11
+ Sorter a LinguaGraph by un-ambiguous topology order .
12
+ """
13
+
14
+ def __init__(self):
15
+ """Define edge type priorities"""
16
+
17
+ self.edge_priorities = {
18
+ # Core semantic relations
19
+ 'pred.arg.1': 0, 'pred.arg.2': 1, 'pred.arg.3': 2, 'pred.arg.4': 3,
20
+ 'func.arg': 4, 'variable': 5, 'body': 6,
21
+
22
+ # Predicate relations
23
+ 'copula': 10, 'appositive': 11, 'discourse': 12, 'ref': 13,
24
+ 'repeat': 14, 'vocative': 15, 'nonsense': 16, 'modification': 17,
25
+ 'parataxis': 18, 'index': 19, 'attribute': 20,
26
+
27
+ # As-predicate relations
28
+ 'as:pred.arg': 30, 'as:pred.arg.1': 31, 'as:pred.arg.2': 32,
29
+ 'as:pred.arg.3': 33, 'as:pred.arg.4': 34, 'as:func.arg': 35,
30
+ 'as:copula': 40, 'as:appositive': 41, 'as:discourse': 42,
31
+ 'as:ref': 43, 'as:repeat': 44, 'as:vocative': 45,
32
+ 'as:nonsense': 46, 'as:parataxis': 47, 'as:index': 48,
33
+ 'as:attribute': 49, 'as:modification': 50, 'as:punctuation': 51, 'punctuation': 52,
34
+ 'as:body': 53, 'as:variable': 54,
35
+
36
+ # Punctuation and structural
37
+ 'local': 60, 'tail': 61,
38
+ }
39
+
40
+ missing_labels = set(LinguaGraphEdges) - set(self.edge_priorities.keys())
41
+ if missing_labels:
42
+ raise ValueError(f"Missing edge labels: {missing_labels}")
43
+
44
+ def _get_edge_rank(self, edge_label: str) -> int:
45
+ """
46
+ Rank edge types by importance.
47
+ """
48
+
49
+ return self.edge_priorities[edge_label]
50
+
51
+ def _get_node_rank_info(self, gpg_graph: GPGraph) -> int:
52
+ """
53
+ Get node rank info for a GPGraph.
54
+ """
55
+ noderank_info = dict()
56
+
57
+ for node in reversed(list(gpg_graph.topological_sort())):
58
+ node_words = set()
59
+ if isinstance(node, GPGPhraseNode):
60
+ node_words.update(node.words(with_aux=False))
61
+ for child, _ in gpg_graph.children(node):
62
+ if isinstance(child, GPGPhraseNode):
63
+ node_words.update(child.words(with_aux=False))
64
+ if node_words:
65
+ noderank_info[node.ID] = (tuple(sorted(node_words)), "PHRASE")
66
+ else:
67
+ assert isinstance(node, GPGAuxNode), "node must be a aux node"
68
+ noderank_info[node.ID] = ((-100,), node.label)
69
+ return noderank_info
70
+
71
+
72
+ def edges(self, lingua_graph: GPGraph) -> List[Tuple[GPGNode, GPGEdge, GPGNode]]:
73
+ """
74
+ Sort edges based on breadth-first search traversal with edge priorities.
75
+ Ensures uniqueness by processing nodes level-by-level and sorting children
76
+ by edge priority (with node ID as tie-breaker) before processing.
77
+ """
78
+ root = lingua_graph.root
79
+ visited = set()
80
+ queue = deque([root])
81
+ visited.add(root.ID)
82
+
83
+ noderank_info = self._get_node_rank_info(lingua_graph)
84
+
85
+ while queue:
86
+ node = queue.popleft()
87
+
88
+ # Get all children and sort by edge priority, node rank, then node ID for uniqueness
89
+ children = list(lingua_graph.children(node))
90
+ children.sort(key=lambda child_edge: (
91
+ self._get_edge_rank(child_edge[1].label), # Primary: edge priority
92
+ noderank_info[child_edge[0].ID], # Secondary: node rank (position/label)
93
+ child_edge[0].ID, # Tie-breaker: node ID
94
+ ))
95
+
96
+ # Yield edges and enqueue children
97
+ for child, edge in children:
98
+ yield (node, edge, child)
99
+
100
+ # Add child to queue if not already visited
101
+ if child.ID not in visited:
102
+ visited.add(child.ID)
103
+ queue.append(child)
104
+
105
+ def nodes(self, lingua_graph: GPGraph) -> List[GPGNode]:
106
+ """
107
+ Sort nodes by topology, ensuring each node is yielded only after all its parents.
108
+ Maintains the same ordering as edges() for nodes at the same level.
109
+ """
110
+ # 1. Calculate in-degrees
111
+ in_degree = {node.ID: 0 for node in lingua_graph.nodes()}
112
+ for node in lingua_graph.nodes():
113
+ for child, _ in lingua_graph.children(node):
114
+ in_degree[child.ID] += 1
115
+
116
+ # 2. Get rank info
117
+ noderank_info = self._get_node_rank_info(lingua_graph)
118
+
119
+ # 3. BFS-based Kahn's Algorithm
120
+ queue = deque([lingua_graph.root])
121
+ visited = {lingua_graph.root.ID}
122
+
123
+ while queue:
124
+ node = queue.popleft()
125
+ yield node
126
+
127
+ # Get children and sort exactly like in edges()
128
+ children = list(lingua_graph.children(node))
129
+ children.sort(key=lambda child_edge: (
130
+ self._get_edge_rank(child_edge[1].label),
131
+ noderank_info[child_edge[0].ID],
132
+ child_edge[0].ID,
133
+ ))
134
+
135
+ for child, edge in children:
136
+ in_degree[child.ID] -= 1
137
+ if in_degree[child.ID] == 0:
138
+ if child.ID not in visited:
139
+ visited.add(child.ID)
140
+ queue.append(child)
model.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model definitions for Word-Lingua Graph Parser
3
+
4
+ This module contains all model-related classes and constants.
5
+ """
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from typing import Dict, Optional
10
+
11
+
12
+ # ============================================================================
13
+ # Node Type Constants
14
+ # ============================================================================
15
+
16
+ # Node types (pos) in word-lingua-graph
17
+ NODE_TYPES = [
18
+ "NominalConstant",
19
+ "FactualPredicator",
20
+ "ModificationalFunctor",
21
+ "PunctuationalConstant",
22
+ "DeterminerConstant",
23
+ "ModificationalConstant",
24
+ "ConjunctionalFunctor",
25
+ "GeneralFunctor",
26
+ "LogicalPredicator",
27
+ "ExpressionFunctor",
28
+ "SymbolConstant",
29
+ "OtherConstant",
30
+ "InterjectionConstant",
31
+ "AttributePredicator",
32
+ ]
33
+
34
+ # Build node type mappings
35
+ NODE_TYPE2ID = {nt: i for i, nt in enumerate(NODE_TYPES)}
36
+ NODE_TYPE2ID["UNK"] = len(NODE_TYPES)
37
+ ID2NODE_TYPE = {v: k for k, v in NODE_TYPE2ID.items()}
38
+
39
+
40
+ # ============================================================================
41
+ # Bilinear Module
42
+ # ============================================================================
43
+
44
+ class PairwiseBilinear(nn.Module):
45
+ """Pairwise bilinear layer for biaffine attention."""
46
+
47
+ def __init__(self, in1_features: int, in2_features: int,
48
+ out_features: int, bias_x: bool = True, bias_y: bool = True):
49
+ super().__init__()
50
+ self.bias_x = bias_x
51
+ self.bias_y = bias_y
52
+ self.in1_features = in1_features
53
+ self.in2_features = in2_features
54
+ self.out_features = out_features
55
+
56
+ self.weight = nn.Parameter(
57
+ torch.zeros(out_features, in1_features + int(bias_x), in2_features + int(bias_y))
58
+ )
59
+ bound = 1 / (self.in1_features * self.in2_features) ** 0.25
60
+ nn.init.uniform_(self.weight, -bound, bound)
61
+
62
+ def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
63
+ if self.bias_x:
64
+ x1 = torch.cat([x1, torch.ones_like(x1[..., :1])], dim=-1)
65
+ if self.bias_y:
66
+ x2 = torch.cat([x2, torch.ones_like(x2[..., :1])], dim=-1)
67
+
68
+ return torch.einsum('bxi,oij,byj->bxyo', x1, self.weight, x2)
69
+
70
+
71
+ # ============================================================================
72
+ # MLP Module
73
+ # ============================================================================
74
+
75
+ class MLP(nn.Module):
76
+ """Multi-layer perceptron with dropout."""
77
+
78
+ def __init__(self, input_size: int, hidden_size: int,
79
+ dropout: float = 0.1, activation: nn.Module = nn.ReLU):
80
+ super().__init__()
81
+ self.layers = nn.Sequential(
82
+ nn.Linear(input_size, hidden_size),
83
+ activation(),
84
+ nn.Dropout(p=dropout)
85
+ )
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ return self.layers(x)
89
+
90
+
91
+ # ============================================================================
92
+ # Biaffine Layer
93
+ # ============================================================================
94
+
95
+ class BiaffineLayer(nn.Module):
96
+ """Biaffine attention layer for arc and relation prediction."""
97
+
98
+ def __init__(self, input_size: int, label_num: int,
99
+ arc_hidden_size: int = 500, rel_hidden_size: int = 100,
100
+ dropout: float = 0.1):
101
+ super().__init__()
102
+ self.label_num = label_num
103
+
104
+ # MLPs for arc prediction
105
+ self.mlp_arc_h = MLP(input_size, arc_hidden_size, dropout)
106
+ self.mlp_arc_d = MLP(input_size, arc_hidden_size, dropout)
107
+
108
+ # MLPs for relation prediction
109
+ self.mlp_rel_h = MLP(input_size, rel_hidden_size, dropout)
110
+ self.mlp_rel_d = MLP(input_size, rel_hidden_size, dropout)
111
+
112
+ # Bilinear layers
113
+ self.arc_atten = PairwiseBilinear(arc_hidden_size, arc_hidden_size, 1)
114
+ self.rel_atten = PairwiseBilinear(rel_hidden_size, rel_hidden_size, label_num)
115
+
116
+ def forward(self, input: torch.Tensor,
117
+ attention_mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
118
+ """
119
+ Args:
120
+ input: (batch, seq_len, hidden_size)
121
+ attention_mask: (batch, seq_len) - True for valid tokens
122
+
123
+ Returns:
124
+ dict with arc_logits (batch, seq_len, seq_len) and
125
+ rel_logits (batch, seq_len, seq_len, label_num)
126
+ """
127
+ # Compute representations for arc prediction
128
+ arc_h = self.mlp_arc_h(input) # head
129
+ arc_d = self.mlp_arc_d(input) # dependent
130
+
131
+ # Compute representations for relation prediction
132
+ rel_h = self.mlp_rel_h(input)
133
+ rel_d = self.mlp_rel_d(input)
134
+
135
+ # Compute arc scores: (batch, seq_len, seq_len, 1) -> (batch, seq_len, seq_len)
136
+ s_arc = self.arc_atten(arc_d, arc_h).squeeze(-1)
137
+
138
+ # Compute relation scores: (batch, seq_len, seq_len, label_num)
139
+ s_rel = self.rel_atten(rel_d, rel_h)
140
+
141
+ # Create pairwise mask if attention_mask is provided
142
+ if attention_mask is not None:
143
+ pairwise_mask = attention_mask.unsqueeze(-1) & attention_mask.unsqueeze(-2)
144
+ s_rel = s_rel.masked_fill(~pairwise_mask.unsqueeze(-1), -1e9)
145
+ else:
146
+ pairwise_mask = None
147
+
148
+ return {
149
+ "arc_logits": s_arc,
150
+ "rel_logits": s_rel,
151
+ "mask": pairwise_mask
152
+ }
153
+
154
+
155
+ # ============================================================================
156
+ # Node Classifier (for child_of_whether and is_root)
157
+ # ============================================================================
158
+
159
+ class NodeClassifier(nn.Module):
160
+ """Classifier for node-level binary attributes."""
161
+
162
+ def __init__(self, input_size: int, hidden_size: int = 256,
163
+ dropout: float = 0.1, num_classes: int = 2):
164
+ super().__init__()
165
+ self.classifier = nn.Sequential(
166
+ nn.Linear(input_size, hidden_size),
167
+ nn.ReLU(),
168
+ nn.Dropout(dropout),
169
+ nn.Linear(hidden_size, num_classes)
170
+ )
171
+
172
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
173
+ """
174
+ Args:
175
+ x: (batch, seq_len, hidden_size)
176
+ Returns:
177
+ logits: (batch, seq_len, num_classes)
178
+ """
179
+ return self.classifier(x)
180
+
181
+
182
+ # ============================================================================
183
+ # Word-Lingua Parser Model (v2)
184
+ # ============================================================================
185
+
186
+ class WordLinguaParserV2(nn.Module):
187
+ """
188
+ BERT-based parser for word-lingua-graph prediction.
189
+
190
+ This version adds:
191
+ - child_of_whether prediction (node-level binary classification)
192
+ - is_root prediction (node-level binary classification)
193
+ - node_type prediction (node-level multi-class classification)
194
+ """
195
+
196
+ def __init__(self, bert_model_name: str, label_num: int,
197
+ num_node_types: int = len(NODE_TYPE2ID),
198
+ arc_hidden_size: int = 500, rel_hidden_size: int = 100,
199
+ node_hidden_size: int = 256,
200
+ dropout: float = 0.1, word_pooling: str = "mean"):
201
+ super().__init__()
202
+
203
+ from transformers import AutoModel
204
+
205
+ self.bert = AutoModel.from_pretrained(bert_model_name)
206
+ hidden_size = self.bert.config.hidden_size
207
+ self.word_pooling = word_pooling
208
+
209
+ # Biaffine layer for arc and relation prediction
210
+ self.biaffine = BiaffineLayer(
211
+ input_size=hidden_size,
212
+ label_num=label_num,
213
+ arc_hidden_size=arc_hidden_size,
214
+ rel_hidden_size=rel_hidden_size,
215
+ dropout=dropout
216
+ )
217
+
218
+ # Node classifiers
219
+ self.child_of_whether_classifier = NodeClassifier(
220
+ input_size=hidden_size,
221
+ hidden_size=node_hidden_size,
222
+ dropout=dropout,
223
+ num_classes=2
224
+ )
225
+
226
+ self.is_root_classifier = NodeClassifier(
227
+ input_size=hidden_size,
228
+ hidden_size=node_hidden_size,
229
+ dropout=dropout,
230
+ num_classes=2
231
+ )
232
+
233
+ # Node type classifier (multi-class)
234
+ self.node_type_classifier = NodeClassifier(
235
+ input_size=hidden_size,
236
+ hidden_size=node_hidden_size,
237
+ dropout=dropout,
238
+ num_classes=num_node_types
239
+ )
240
+
241
+ self.dropout = nn.Dropout(dropout)
242
+
243
+ def aggregate_subwords(self, hidden_states: torch.Tensor,
244
+ word_to_subword: torch.Tensor,
245
+ word_mask: torch.Tensor) -> torch.Tensor:
246
+ """
247
+ Aggregate subword embeddings to word-level representations.
248
+
249
+ Memory-efficient implementation that avoids creating large intermediate tensors.
250
+ """
251
+ batch_size, max_words, max_subwords = word_to_subword.shape
252
+ hidden_size = hidden_states.size(-1)
253
+ device = hidden_states.device
254
+
255
+ # Create output tensor
256
+ word_repr = torch.zeros(batch_size, max_words, hidden_size, device=device, dtype=hidden_states.dtype)
257
+
258
+ # Get valid subword mask
259
+ subword_mask = (word_to_subword >= 0) # [batch, max_words, max_subwords]
260
+ safe_indices = word_to_subword.clamp(min=0) # [batch, max_words, max_subwords]
261
+
262
+ if self.word_pooling == "first":
263
+ # Simply take the first subword for each word
264
+ first_indices = safe_indices[:, :, 0] # [batch, max_words]
265
+ # Gather from hidden_states: [batch, seq_len, hidden] -> [batch, max_words, hidden]
266
+ gather_indices = first_indices.unsqueeze(-1).expand(-1, -1, hidden_size)
267
+ word_repr = torch.gather(hidden_states, dim=1, index=gather_indices)
268
+
269
+ elif self.word_pooling == "last":
270
+ # Take the last valid subword for each word
271
+ num_subwords = subword_mask.sum(dim=2).clamp(min=1) # [batch, max_words]
272
+ last_subword_pos = num_subwords - 1 # [batch, max_words]
273
+ # Get the index from safe_indices at the last valid position
274
+ last_indices = torch.gather(safe_indices, dim=2,
275
+ index=last_subword_pos.unsqueeze(-1)).squeeze(-1) # [batch, max_words]
276
+ gather_indices = last_indices.unsqueeze(-1).expand(-1, -1, hidden_size)
277
+ word_repr = torch.gather(hidden_states, dim=1, index=gather_indices)
278
+
279
+ elif self.word_pooling in ["mean", "max"]:
280
+ # For mean/max pooling, we need to gather all subwords
281
+ # But we do it more efficiently by flattening and using scatter/gather
282
+
283
+ # Flatten indices: [batch, max_words * max_subwords]
284
+ flat_indices = safe_indices.view(batch_size, -1) # [batch, max_words * max_subwords]
285
+ flat_mask = subword_mask.view(batch_size, -1) # [batch, max_words * max_subwords]
286
+
287
+ # Gather all subword embeddings at once
288
+ gather_indices = flat_indices.unsqueeze(-1).expand(-1, -1, hidden_size)
289
+ flat_embeds = torch.gather(hidden_states, dim=1, index=gather_indices) # [batch, max_words * max_subwords, hidden]
290
+
291
+ # Reshape back to [batch, max_words, max_subwords, hidden]
292
+ subword_embeds = flat_embeds.view(batch_size, max_words, max_subwords, hidden_size)
293
+ subword_mask_expanded = subword_mask.unsqueeze(-1) # [batch, max_words, max_subwords, 1]
294
+
295
+ if self.word_pooling == "mean":
296
+ subword_embeds = subword_embeds * subword_mask_expanded.float()
297
+ word_repr = subword_embeds.sum(dim=2)
298
+ num_subwords = subword_mask.sum(dim=2, keepdim=True).clamp(min=1).float()
299
+ word_repr = word_repr / num_subwords
300
+ else: # max
301
+ subword_embeds = subword_embeds.masked_fill(~subword_mask_expanded, float('-inf'))
302
+ word_repr = subword_embeds.max(dim=2)[0]
303
+ else:
304
+ raise ValueError(f"Unknown word_pooling: {self.word_pooling}")
305
+
306
+ return word_repr
307
+
308
+ def forward(self, input_ids: torch.Tensor,
309
+ attention_mask: torch.Tensor,
310
+ word_to_subword: torch.Tensor,
311
+ word_mask: torch.Tensor) -> Dict[str, torch.Tensor]:
312
+ """
313
+ Returns:
314
+ dict with arc_logits, rel_logits, child_of_whether_logits, is_root_logits, node_type_logits
315
+ """
316
+ # Get BERT outputs
317
+ outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
318
+ hidden_states = outputs.last_hidden_state
319
+ hidden_states = self.dropout(hidden_states)
320
+
321
+ # Aggregate subword embeddings to word-level representations
322
+ word_repr = self.aggregate_subwords(hidden_states, word_to_subword, word_mask)
323
+
324
+ # Apply biaffine attention for arc/relation prediction
325
+ biaffine_result = self.biaffine(word_repr, word_mask)
326
+
327
+ # Node-level predictions
328
+ child_of_whether_logits = self.child_of_whether_classifier(word_repr)
329
+ is_root_logits = self.is_root_classifier(word_repr)
330
+ node_type_logits = self.node_type_classifier(word_repr)
331
+
332
+ return {
333
+ "arc_logits": biaffine_result["arc_logits"],
334
+ "rel_logits": biaffine_result["rel_logits"],
335
+ "mask": biaffine_result["mask"],
336
+ "child_of_whether_logits": child_of_whether_logits,
337
+ "is_root_logits": is_root_logits,
338
+ "node_type_logits": node_type_logits,
339
+ }
340
+
requirements.txt CHANGED
@@ -1,6 +1,8 @@
1
- accelerate
2
- diffusers
3
- invisible_watermark
4
- torch
5
- transformers
6
- xformers
 
 
 
1
+ torch>=2.0.0
2
+ transformers>=4.30.0
3
+ gradio>=4.0.0
4
+ huggingface-hub>=0.16.0
5
+ numpy>=1.24.0
6
+ jsonlines>=3.1.0
7
+ networkx>=3.0
8
+