File size: 10,913 Bytes
9d2f453
 
 
e85ab8f
 
 
 
 
 
9d2f453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85ab8f
 
 
 
9d2f453
 
 
 
 
 
 
e85ab8f
9d2f453
e85ab8f
 
 
 
 
9d2f453
 
e85ab8f
9d2f453
e85ab8f
9d2f453
 
 
e85ab8f
9d2f453
 
 
 
e85ab8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d2f453
e85ab8f
9d2f453
 
 
 
 
 
 
 
e85ab8f
9d2f453
 
 
 
 
 
 
e85ab8f
9d2f453
 
e85ab8f
9d2f453
 
 
 
 
e85ab8f
9d2f453
 
 
 
 
 
 
 
 
 
 
 
e85ab8f
9d2f453
 
 
 
e85ab8f
 
 
 
9d2f453
 
 
e85ab8f
9d2f453
e85ab8f
 
 
 
9d2f453
 
 
 
 
 
 
e85ab8f
9d2f453
 
 
 
 
e85ab8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d2f453
 
 
 
 
 
 
 
e85ab8f
9d2f453
 
 
 
e85ab8f
9d2f453
e85ab8f
9d2f453
e85ab8f
 
 
 
9d2f453
 
 
 
 
e85ab8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d2f453
 
 
 
 
 
e85ab8f
 
 
 
 
 
 
9d2f453
 
e85ab8f
 
 
 
9d2f453
e85ab8f
 
9d2f453
e85ab8f
9d2f453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85ab8f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import math
from spacy.tokens import Doc, Token

# Gruppi di tempi italiani per la consecutio temporum
_IT_PRES_GROUP = {"Pres", "Fut", "FutPerf", "SubPres", "SubPerf"}
_IT_PAST_GROUP = {"Imp", "Past", "Perf", "PluPerf", "PastPerf",
                  "SubImp", "SubPluPerf", "Cnd", "CndPerf"}


class ConsecutioAnalyzer:
    def __init__(self):
        self.reset_metrics()

    def reset_metrics(self):
        self.total_sentences = 0
        self.sum_max_depth = 0
        self.total_verb_pairs = 0
        self.valid_consecutio_pairs = 0
        self.total_words = 0
        self.total_verb_groups = 0
        self.root_tenses_list = []

    class TokenNode:
        def __init__(self, spacy_token):
            self.id = str(spacy_token.i)
            self.form = spacy_token.text
            self.lemma = spacy_token.lemma_.lower()
            self.pos_tag = spacy_token.tag_   # Penn Treebank (EN) / UD tag (IT)
            self.pos_ = spacy_token.pos_
            self.morph = spacy_token.morph
            self.dep_rel = spacy_token.dep_
            self.head_id = str(spacy_token.head.i) if spacy_token.head.i != spacy_token.i else "0"
            self.children = []
            self.compound_tense = ""
            self.is_compound_head = False

        def is_verb(self):
            # Penn Treebank (EN)
            return self.pos_tag.startswith("V") or self.pos_tag.startswith("MD") or self.pos_tag == "AUX"

        def is_verb_it(self):
            # Universal Dependencies (IT): usa pos_ invece di tag_
            return self.pos_ in {"VERB", "AUX"}

        def is_auxiliary_rel(self):
            return "aux" in self.dep_rel.lower()

        def get_simple_tense(self):
            # Penn Treebank tags (EN)
            tag = self.pos_tag
            if tag in ["VBD", "VBN"]: return "Past"
            if tag in ["VBP", "VBZ"]: return "Pres"
            if tag == "VBG": return "Ger"
            if tag == "MD": return "Mod"
            if tag == "VB": return "Inf"
            return "N/A"

        def get_simple_tense_it(self):
            # Universal Dependencies morphology (IT)
            mood = (self.morph.get("Mood") or [None])[0]
            tense = (self.morph.get("Tense") or [None])[0]
            verb_form = (self.morph.get("VerbForm") or [None])[0]
            if verb_form == "Part" and tense == "Past": return "Part"
            if verb_form == "Inf":  return "Inf"
            if verb_form == "Ger":  return "Ger"
            if mood == "Ind":
                if tense == "Pres": return "Pres"
                if tense == "Imp":  return "Imp"
                if tense == "Past": return "Past"
                if tense == "Fut":  return "Fut"
            if mood == "Sub":
                if tense == "Pres": return "SubPres"
                if tense == "Past": return "SubPast"
                if tense == "Imp":  return "SubImp"
            if mood == "Cnd": return "Cnd"
            return "N/A"

    def analyze(self, doc, lang="en"):
        self.reset_metrics()

        for sent in doc.sents:
            self.total_sentences += 1
            words_in_sent = [t for t in sent if not t.is_punct]
            self.total_words += len(words_in_sent)

            try:
                node_map = {str(t.i): self.TokenNode(t) for t in sent}
                root = None

                for node in node_map.values():
                    if node.head_id == "0" or node.dep_rel.lower() == "root":
                        root = node
                    elif node.head_id in node_map:
                        node_map[node.head_id].children.append(node)

                if root:
                    self._process_compound_tenses(root, lang)
                    self.root_tenses_list.append(root.compound_tense)
                    self.sum_max_depth += self._calculate_tree_depth(root)
                    self._check_consecutio_recursively(root, lang)
                else:
                    self.root_tenses_list.append("N/A")
            except Exception:
                continue

        stability = self._calculate_dominant_stability(lang)
        avg_depth = self.sum_max_depth / self.total_sentences if self.total_sentences > 0 else 0.0
        consecutio_score = self.valid_consecutio_pairs / self.total_verb_pairs if self.total_verb_pairs > 0 else 1.0
        verb_density = self.total_verb_groups / self.total_words if self.total_words > 0 else 0.0
        sentence_depths = self.calculate_average_graph_depth(doc)
        return {
            "tense_stability": round(stability, 4),
            "avg_depth": round(avg_depth, 4) if self.total_sentences > 0 else 0.0,
            "consecutio_index": round(consecutio_score, 4),
            "verb_density": round(verb_density, 4),
            "sentence_depths": round(sentence_depths, 4)
        }

    def _process_compound_tenses(self, node, lang="en"):
        aux_children = []
        for child in node.children:
            if child.is_auxiliary_rel():
                aux_children.append(child)
            self._process_compound_tenses(child, lang)

        is_v = node.is_verb_it() if lang == "it" else node.is_verb()
        if is_v and not node.is_auxiliary_rel():
            node.is_compound_head = True
            self.total_verb_groups += 1
            group = [node] + aux_children
            node.compound_tense = self._infer_compound_tense(group, node, lang)

    def _infer_compound_tense(self, group, head, lang="en"):
        if lang == "it":
            return self._infer_compound_tense_it(group, head)
        # English (Penn Treebank)
        has_will, has_have, has_modal = False, False, False
        for n in group:
            if n == head: continue
            f = n.form.lower()
            if "will" in f or "'ll" in f: has_will = True
            elif any(x in f for x in ["have", "has", "had"]): has_have = True
            elif n.pos_tag == "MD": has_modal = True

        if has_modal: return "Mod"
        if has_will: return "Fut"
        if has_have and head.pos_tag == "VBN": return "Perf"
        return head.get_simple_tense()

    def _infer_compound_tense_it(self, group, head):
        """
        Riconosce i tempi composti italiani dall'ausiliare + participio passato.

        Regole:
          avere/essere Pres  + Part → Perf        (passato prossimo)
          avere/essere Imp   + Part → PluPerf      (trapassato prossimo)
          avere/essere Past  + Part → PastPerf     (trapassato remoto)
          avere/essere Fut   + Part → FutPerf      (futuro anteriore)
          avere/essere SubPres + Part → SubPerf    (cong. passato)
          avere/essere SubImp + Part → SubPluPerf  (cong. trapassato)
          avere/essere Cnd  + Part → CndPerf       (cond. passato)
        """
        head_simple = head.get_simple_tense_it()
        if head_simple == "Part":
            for n in group:
                if n == head: continue
                aux_t = n.get_simple_tense_it()
                if aux_t == "Pres":    return "Perf"
                if aux_t == "Imp":     return "PluPerf"
                if aux_t == "Past":    return "PastPerf"
                if aux_t == "Fut":     return "FutPerf"
                if aux_t == "SubPres": return "SubPerf"
                if aux_t == "SubImp":  return "SubPluPerf"
                if aux_t == "Cnd":     return "CndPerf"
            return "Part"
        return head_simple

    def _calculate_tree_depth(self, node):
        if not node.children: return 1
        max_d = 0
        for child in node.children:
            if child.is_auxiliary_rel(): continue
            max_d = max(max_d, self._calculate_tree_depth(child))
        return 1 + max_d

    def _check_consecutio_recursively(self, parent, lang="en"):
        for child in parent.children:
            if child.is_auxiliary_rel(): continue
            if parent.is_compound_head and child.is_compound_head:
                self.total_verb_pairs += 1
                if self._is_consecutio_valid(parent.compound_tense, child.compound_tense, lang):
                    self.valid_consecutio_pairs += 1
            self._check_consecutio_recursively(child, lang)

    def _is_consecutio_valid(self, p, c, lang="en"):
        if lang == "it":
            return self._is_consecutio_valid_it(p, c)
        # English
        if self._is_pres_group(p): return True
        if self._is_past_group(p):
            if c == "Pres" or c == "Ger": return False
        return True

    def _is_consecutio_valid_it(self, p, c):
        """
        Regole di concordanza dei tempi italiani.

        Tabella reggente → subordinata:
          Presente/futuro (gruppo pres.) → qualsiasi tempo è valido.
          Passato/imperfetto/perfetto (gruppo past.) → subordinata deve
          usare gruppo passato (cong. imperfetto, trapassato, condizionale…).
          Forme non finite (Inf, Ger, Part) → sempre valide.
        """
        if c in {"Inf", "Ger", "Part", "N/A"}: return True
        if self._is_pres_group_it(p): return True
        if self._is_past_group_it(p):
            return not self._is_pres_group_it(c)
        return True

    def _is_past_group(self, t):
        return "Past" in t or "Perf" in t or "Mod" in t

    def _is_pres_group(self, t):
        return "Pres" in t or "Fut" in t or "Ger" in t

    def _is_past_group_it(self, t):
        return t in _IT_PAST_GROUP

    def _is_pres_group_it(self, t):
        return t in _IT_PRES_GROUP

    def _calculate_dominant_stability(self, lang="en"):
        valid_roots = [t for t in self.root_tenses_list if t != "N/A"]
        if not valid_roots: return 0.0
        is_past = self._is_past_group_it if lang == "it" else self._is_past_group
        is_pres = self._is_pres_group_it if lang == "it" else self._is_pres_group
        past_c = sum(1 for t in valid_roots if is_past(t))
        pres_c = sum(1 for t in valid_roots if is_pres(t))
        dom_past = past_c >= pres_c
        aligned = sum(1 for t in valid_roots if
                      (dom_past and is_past(t)) or (not dom_past and is_pres(t)))
        return aligned / len(valid_roots)

    @staticmethod
    def calculate_average_graph_depth(doc: Doc) -> float:
        total_depth = 0
        total_nodes = 0

        for sent in doc.sents:
            depths = {}
            for token in sent:
                depths[token.i] = ConsecutioAnalyzer._get_token_depth(token, depths)
                total_depth += depths[token.i]
            total_nodes += len(sent)

        return total_depth / total_nodes if total_nodes > 0 else 0.0

    @staticmethod
    def _get_token_depth(token: Token, depths: dict) -> int:
        if token.i in depths:
            return depths[token.i]

        if token.head == token:
            depths[token.i] = 1
            return 1

        depth = ConsecutioAnalyzer._get_token_depth(token.head, depths) + 1
        depths[token.i] = depth
        return depth