|
| 1 | +# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project |
| 2 | +# SPDX-FileType: SOURCE |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +"""Attaparse: Thai dependency parser based on Stanza and PhayaThaiBERT. |
| 5 | +
|
| 6 | +GitHub: https://github.com/nlp-chula/attaparse |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from typing import TYPE_CHECKING, List, Union |
| 12 | + |
| 13 | +try: |
| 14 | + from attaparse import depparse, load_model |
| 15 | +except ImportError: |
| 16 | + raise ImportError( |
| 17 | + "Import Error; Install attaparse by pip install attaparse" |
| 18 | + ) |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from stanza import Pipeline |
| 22 | + |
| 23 | + |
| 24 | +class Parse: |
| 25 | + def __init__(self) -> None: |
| 26 | + self.nlp: Pipeline = load_model() |
| 27 | + |
| 28 | + def __call__( |
| 29 | + self, text: str, tag: str = "str" |
| 30 | + ) -> Union[List[List[str]], str]: |
| 31 | + doc = depparse(text, self.nlp) |
| 32 | + rows = [] |
| 33 | + for sent in doc.sentences: |
| 34 | + for word in sent.words: |
| 35 | + row = [ |
| 36 | + str(word.id), |
| 37 | + word.text, |
| 38 | + word.lemma if word.lemma else "_", |
| 39 | + word.upos if word.upos else "_", |
| 40 | + word.xpos if word.xpos else "_", |
| 41 | + word.feats if word.feats else "_", |
| 42 | + str(word.head), |
| 43 | + word.deprel if word.deprel else "_", |
| 44 | + "_", # DEPS (enhanced dependencies, not provided) |
| 45 | + "SpaceAfter=No", # MISC: Thai text has no inter-word spaces |
| 46 | + ] |
| 47 | + rows.append(row) |
| 48 | + if tag == "list": |
| 49 | + return rows |
| 50 | + return "\n".join("\t".join(row) for row in rows) |
0 commit comments