# /// script # requires-python = ">=3.12" # dependencies = [ # "aozora-corpus-generator==0.1.1", # "cdifflib==1.2.9", # "ginza", # "ja-ginza", # "ipython==7.23.1", # "marimo", # "polars==1.30.0", # "spacy==3.8.7", # "wcwidth", # ] # # [tool.uv.sources] # aozora-corpus-generator = { git = "https://github.com/borh/aozora-corpus-generator.git" } # /// import marimo __generated_with = "0.13.15" app = marimo.App() @app.cell(hide_code=True) def _(mo): mo.md( rf""" # Aozora Bunko Text Processing Pipeline Demo / 青空文庫テキストの前処理パイプラインデモ ### Summary This notebook allows you to upload, preprocess, compare, visualize and analyze Aozora Bunko texts. 1. Upload a text file from Aozora Bunko (or use the default sample). 2. Preprocess using customizable regex patterns. 3. Preview the first and last 50 lines of the cleaned text. 4. Download the cleaned text. 5. Process the XHTML version with the `aozora-corpus-generator` Python library for comparison. 6. Compare against the regex variant. 6. Define token matching patterns (not possible in App mode). 7. Visualize token matches. 8. Define dependency matching patterns (not possible in App mode). 9. Visualize dependency matches. ### 概要 このノートブックでは以下の手順で青空文庫テキストを読み込み、前処理、解析、可視化を行います。 1. 青空文庫のテキストファイルをアップロードする(またはデフォルトサンプルを利用する)。 2. 編集可能な正規表現で前処理する。 3. 前処理済みテキストの先頭50行と末尾50行をプレビューし、前処理が正常に本文以外のテキストを除外したか確認する。 4. 前処理済みテキストをダウンロードする。 5. 比較のため、XHTML版をPythonのパッケージで処理する。 6. 正規表現処理版と比較する。 7. トークンマッチング用パターンを定義する(アプリの場合は編集不可)。 8. トークンマッチ結果を可視化する。 9. 係り受け(依存)関係マッチング用パターンを定義する(アプリの場合は編集不可)。 10. 係り受け関係マッチ結果を可視化する。 """ ) return @app.cell def _(mo): mo.md(''' - By default, this demo uses Natsume Soseki's _‘Wagahai wa neko de aru’_ - ファイルをアップロードしない場合は、デフォルトで夏目漱石『吾輩は猫である』が使用されます。 ''').callout(kind="info") return @app.cell def _(): import re import marimo as mo import polars as pl import spacy from spacy.tokens import Doc nlp = spacy.load( "ja_ginza" ) # or "ja_ginza_electra"/"ja_ginza_bert_large" if installed return Doc, mo, nlp, pl, re, spacy @app.cell def upload_aozora_text(mo): aozora_file = mo.ui.file(label="Upload Aozora-Bunko text (.txt)", multiple=False) return (aozora_file,) @app.cell def select_encoding(mo): """ Let the user choose the text‐file encoding. """ encoding = mo.ui.dropdown( options=["shift-jis", "utf-8"], value="shift-jis", label="Text file encoding / 文字コード", full_width=False, ) return (encoding,) @app.cell def _(aozora_file, encoding, mo): ab_upload_ui = mo.hstack([aozora_file, encoding]) mo.md(f"## 青空文庫テキストファイル設定\n{ab_upload_ui}") return @app.cell def load_aozora_text(aozora_file, encoding): """ Load the uploaded file if provided; otherwise read the local wagahaiwa_nekodearu.txt. Returns the raw text. """ enc = encoding.value if aozora_file.value: uploaded = aozora_file.contents() text_raw = uploaded.decode(enc) else: with open("wagahaiwa_nekodearu.txt", encoding="shift-jis") as f: text_raw = f.read() return (text_raw,) @app.cell def show_raw_head(mo, text_raw): mo.md( f""" ## 青空文庫のヘッダーとフッターを確認 最初の500字 ```raw {text_raw[:500]} ``` 最後の500字 ```raw {text_raw[-500:]} ``` """ ) return @app.cell def regex_inputs(mo): ruby_pattern = mo.ui.text( value=r"《[^》]+》", label="ルビ", full_width=True, ) ruby_bar_pattern = mo.ui.text( value=r"|", label="ルビのかかる範囲を示す記号", full_width=True, ) annotation_pattern = mo.ui.text( value=r"[#[^]]+?]", label="注釈・アノテーション", full_width=True, ) hajime_pattern = mo.ui.text( value=r"-{55}(.|\n)+?-{55}", label="青空文庫のヘッダー", full_width=True, ) owari_pattern = mo.ui.text( value=( r"^[ 【]?(底本:|訳者あとがき|この翻訳は|この作品.*翻訳|" r"この翻訳.*全訳)" ), label="青空文庫のフッター", full_width=True, ) regexes = mo.vstack( [ ruby_pattern, ruby_bar_pattern, annotation_pattern, hajime_pattern, owari_pattern, ] ) mo.md(f"""## 正規表現による前処理 (必要な場合は修正) {regexes} """) return ( annotation_pattern, hajime_pattern, owari_pattern, ruby_bar_pattern, ruby_pattern, ) @app.cell def clean_aozora( annotation_pattern, hajime_pattern, mo, owari_pattern, re, ruby_bar_pattern, ruby_pattern, text_raw, ): # compile from user‐editable patterns ruby_rx = re.compile(ruby_pattern.value) ruby_bar_rx = re.compile(ruby_bar_pattern.value) annotation_rx = re.compile(annotation_pattern.value) hajime_rx = re.compile(hajime_pattern.value) owari_rx = re.compile(owari_pattern.value, re.M) def clean_text(text: str) -> tuple[str, str, str]: """青空文庫テキスト形式の文字列textを入力とし,改行方式の統一,ルビーと各種のアノーテーションの削除, 青空文庫特有のヘッダーとフッターを取り除く処理を行う。""" title, author, text = (text.split("\n", 2) + ["", ""])[:3] # 青空文庫では改行がDOS形式の\r\nのため,それをUNIX形式の\nに統一する。 cleaned_text = re.sub(r"(\r\n)+", "\n", text) # ルビ《...》の記号とその中身を削除 cleaned_text = re.sub(ruby_rx, "", cleaned_text) # ルビのもう一つの書き方に対応:「一番|獰悪《どうあく》」 cleaned_text = re.sub(ruby_bar_rx, "", cleaned_text) # 注釈対応:「※[#「言+墟のつくり」、第4水準2-88-74]」 cleaned_text = re.sub(annotation_rx, "", cleaned_text) # 本文までのテキストを削除 cleaned_text = re.sub(hajime_rx, "", cleaned_text) # 本文の後のテキストを削除 maybe_owari = owari_rx.search(cleaned_text) if maybe_owari: return (title, author, cleaned_text[0 : maybe_owari.start()].strip()) return (title, author, cleaned_text.strip()) title, author, cleaned_text = clean_text(text_raw) mo.md(f"""### 前処理結果の確認 - 著者:`{author}` - タイトル:`{title}` 最初の100字 ```raw {cleaned_text[:100]} ``` 最後の100字 ```raw {cleaned_text[-100:]} ``` """) return author, cleaned_text, title @app.cell def download_cleaned_text(author, cleaned_text, mo, title): """ Provide a download link for the cleaned Aozora text. """ download_link = mo.download( data=cleaned_text.encode("utf-8"), filename=f"{author}_{title}.txt", mimetype="text/plain", ) mo.md(f""" 前処理済みファイルのダウンロード (UTF-8): {download_link} """) return @app.cell def get_alternative_file(mo): aozora_xhtml_file = mo.ui.file( label="Upload Aozora-Bunko text (.html)", multiple=False ) xhtml_encoding = mo.ui.dropdown( options=["shift-jis", "utf-8"], value="shift-jis", label="Text file encoding", full_width=False, ) mo.md(f""" ## HTMLを使用した前処理との比較(オプショナル) プレインテキスト版を正規表現で前処理した結果を、(X)HTML版をPythonで処理した結果を比較したい場合は同じ作品のHTMLファイルをアップします。 {aozora_xhtml_file} {xhtml_encoding} """) return aozora_xhtml_file, xhtml_encoding @app.cell def show_natsume_head(aozora_xhtml_file, mo, xhtml_encoding): from aozora_corpus_generator.aozora import parse_aozora_bunko_xml_content xhtml_enc = xhtml_encoding.value if aozora_xhtml_file.value: uploaded_xhtml = aozora_xhtml_file.contents() xhtml_raw = uploaded_xhtml else: with open("789_14547.html", "rb") as xhtml_f: xhtml_raw = xhtml_f.read() aozora_xhtml_processed = parse_aozora_bunko_xml_content( xhtml_raw, do_tokenize=False ) aozora_xhtml_processed_text = aozora_xhtml_processed["text"] mo.md(f""" HTML版の最初の200字 ```raw {aozora_xhtml_processed_text[:200]} ``` HTML版の最後の200字 ```raw {aozora_xhtml_processed_text[-200:]} ``` """) return (aozora_xhtml_processed_text,) @app.cell def _(aozora_xhtml_processed_text, author, mo, title): xhtml_download_link = mo.download( data=aozora_xhtml_processed_text.encode("utf-8"), filename=f"{author}_{title}_xhtml.txt", mimetype="text/plain", ) mo.md(f""" HTML版の前処理済みファイルをダウンロード (UTF-8): {xhtml_download_link} """) return @app.cell def _(): import difflib import html from cdifflib import CSequenceMatcher from IPython.display import HTML from IPython.display import display_html as display difflib.SequenceMatcher = CSequenceMatcher DEL_STYLE = "background-color:#f6c6c6;color:#000;" # red bg, black text INS_STYLE = "background-color:#c6f6c6;color:#000;" # green bg, black text WRAP_STYLE = ( "font-family: ui-monospace, monospace; " "white-space: pre-wrap; line-height:1.4; color:#000;" ) WS_MAP = str.maketrans({" ": "␣", "\t": "⇥", "\n": "↩\n"}) def _escape(txt: str) -> str: return html.escape(txt.translate(WS_MAP)) def _char_changes(a: str, b: str) -> str: """Return HTML for *only* the changed chars between a and b.""" sm = difflib.SequenceMatcher(None, a, b, autojunk=False) pieces = [] for tag, i1, i2, j1, j2 in sm.get_opcodes(): if tag == "delete": pieces.append(f'{_escape(a[i1:i2])}') elif tag == "insert": pieces.append(f'{_escape(b[j1:j2])}') elif tag == "replace": pieces.append(f'{_escape(a[i1:i2])}') pieces.append(f'{_escape(b[j1:j2])}') # equal → ignore return "".join(pieces) def diff_changes(a: str, b: str, auto_display: bool = True): """ Colab/Jupyter-friendly inline diff that shows *only the changed segments*. Lightning-fast on large, mostly-identical texts. """ a_lines = a.splitlines(keepends=True) b_lines = b.splitlines(keepends=True) outer = difflib.SequenceMatcher(None, a_lines, b_lines, autojunk=True) html_chunks = [] for tag, i1, i2, j1, j2 in outer.get_opcodes(): if tag == "replace": # both sides present for la, lb in zip(a_lines[i1:i2], b_lines[j1:j2]): html_chunks.append(_char_changes(la, lb)) # handle length mismatch for la in a_lines[i1 + (j2 - j1) : i2]: html_chunks.append( f'{_escape(la)}' ) for lb in b_lines[j1 + (i2 - i1) : j2]: html_chunks.append( f'{_escape(lb)}' ) elif tag == "delete": for la in a_lines[i1:i2]: html_chunks.append( f'{_escape(la)}' ) elif tag == "insert": for lb in b_lines[j1:j2]: html_chunks.append( f'{_escape(lb)}' ) # equal → skip entirely (we want only changes) rendered = f'