Skip to content

知らない分野を、原文にたどりつくまで芋づる式に掘る Claude Code のスキル

Python

2.2.0 前のレビューの指摘を直す

MaryCachea598ea6cb9d3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 781868f..b2f5c48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,13 +13,15 @@ imozuruのバージョンごとの変更を記録します。
### 追加
- Codex CLIでの入れ方と呼び方を、日本語・英語のREADMEに追加しました(#18)。
-- `pdftotext` が無い環境で、[pdfminer.six](https://github.com/pdfminer/pdfminer.six) が入っていれば、それでPDFの本文を取り出すようにしました(#15)。popplerを入れられない環境でも、文字の層があるPDFは読めます。`pdftotext` と同じく別の処理として時間の上限つきで動かします。文字の層が無いPDFのOCRには、これまでどおり `pdftoppm` と `tesseract` が要ります。
+- `pdftotext` が無い環境で、[pdfminer.six](https://github.com/pdfminer/pdfminer.six) が入っていれば、それでPDFの本文を取り出すようにしました(#15)。popplerを入れられない環境でも、文字の層があるPDFは読めます。`pdftotext` と同じく別の処理として時間の上限つきで動かします。pdfminer.six を読み込めないときは、PATHにある `pdf2txt.py`(pipxで入れた場合など。Windowsでは使いません)を使います。pdfminer.six は `pdftotext` より遅く、大きなPDFは時間の上限(300秒)で止まって `FAIL` になることがあります。文字の層が無いPDFのOCRには、これまでどおり `pdftoppm` と `tesseract` が要ります。
### 修正
- AIエージェント向けのスキルなどを管理する [APM(Agent Package Manager)](https://github.com/microsoft/apm) で、不可視文字の検出によりインストールが止まる問題を直しました。原文のファイル名を検査する正規表現の双方向制御文字を Unicode エスケープで表記し、危険な名前を拒否する動作を変えずに、`--force` なしでインストールできるようにしました。
-- 原文の行頭の負号を落とした抜き書きが「照合 OK」になる問題を直しました(#19)。`text/plain` で取ってきた原文は `.md` で保存されるため、2.1.0では箇条書きの印と一緒に負号も消していました。数字の前の行頭の `- ` は消さず、負号の直後から始まる抜き書きは通しません。1行目の負号を落とした抜き書きが通る問題は2.1.0より前からあり、これも直しました。数字で始まるMarkdownの項目は、`- ` ごと写したときだけ照合が通ります。
-- ダッシュボードの一覧で、同じ日に始めた調査が新しい順に並ばない問題を直しました。日付が同じときは調査の名前の逆順で並んでいました。最初に保存した原文の時刻で、新しい調査を上に並べます。
+- 原文の行頭の負号を落とした抜き書きが「照合 OK」になる問題を直しました(#19)。`text/plain` で取ってきた原文は `.md` で保存されるため、2.1.0では箇条書きの印と一緒に負号も消していました。数字の前の行頭の `- ` は消さず、負号の直後から始まる抜き書きは通しません。1行目の負号を落とした抜き書きが通る問題は2.1.0より前からあり、これも直しました。負号として扱う字は `-`・`−`(U+2212)・`-`(全角)・`–`(en dash)です。英数字の直後のハイフン(`COVID-19`・`18-65`・2段組のPDFで行末で切った語)は語の一部として扱い、その後ろから写した抜き書きはこれまでどおり通ります。数で始まるMarkdownの項目は、`- ` ごと写したときだけ照合が通ります。照合が通らないときは、負号ごと写すよう案内を出します。
+ 2.1.0で作った調査の抜き書きを照合し直すと、数で始まる箇条書きの項目を `- ` なしで写したものはNGになります(手元の調査では2,053件中4件)。`- ` ごと写し直してください。
+- ダッシュボードの一覧で、同じ日に始めた調査が新しい順に並ばない問題を直しました。日付が同じときは調査の名前の逆順で並んでいました。取得の記録(`fetch-log.jsonl`)に時刻を残すようにし、最初に取得した時刻で新しい調査を上に並べます。時刻の無い前の調査は、最初に保存した原文のファイルの時刻を使います。
+- 検索や取得の記録に、オブジェクトでない行が1行でもあると、ダッシュボードの一覧が開けなくなる問題を直しました。読めない行と同じく飛ばします。
## [2.1.0] - 2026-10-26
diff --git a/README.en.md b/README.en.md
index c5ec293..3d5ad22 100644
--- a/README.en.md
+++ b/README.en.md
@@ -119,7 +119,7 @@ The scripts run on the Python 3.10+ standard library alone, and use the followin
| Command | Used for | When missing |
|---|---|---|
-| `pdftotext` (poppler or Xpdf) | Extracting text from PDFs | Uses [pdfminer.six](https://github.com/pdfminer/pdfminer.six) instead when it is installed (install it into the Python that runs the scripts with `python3 -m pip install --user pdfminer.six`; for environments where poppler cannot be installed). With neither, the fetch reports `FAIL` |
+| `pdftotext` (poppler or Xpdf) | Extracting text from PDFs | Uses [pdfminer.six](https://github.com/pdfminer/pdfminer.six) instead when it is installed (install it into the Python that runs the scripts with `python3 -m pip install --user pdfminer.six`; for environments where poppler cannot be installed). A `pdf2txt.py` on the PATH also works (not on Windows). It is slower than pdftotext, so a large PDF may hit the time limit and report `FAIL`. With none of these, the fetch reports `FAIL` |
| `pdftoppm` (poppler or Xpdf) and `tesseract` | OCR for old PDFs with no text layer | That PDF reports `FAIL` |
| `tesseract` language data `jpn` and `jpn_vert` | Reading Japanese scans, both horizontal and vertical (used automatically when installed; set `IMOZURU_OCR_LANG`, e.g. `jpn+eng`, to choose) | OCR runs in English only; a Japanese PDF reports `FAIL` because the recognition confidence is low |
| `yt-dlp` | Downloading YouTube captions | Videos report `FAIL` |
diff --git a/README.md b/README.md
index 9f503a9..221984c 100644
--- a/README.md
+++ b/README.md
@@ -116,7 +116,7 @@ codex --search exec -s workspace-write -c sandbox_workspace_write.network_access
| コマンド | 使う場面 | 入っていない場合 |
|---|---|---|
-| `pdftotext`(popplerかXpdf) | PDFから本文を取り出す | [pdfminer.six](https://github.com/pdfminer/pdfminer.six) が入っていれば、代わりにそれで取り出す(スクリプトを動かすPythonに `python3 -m pip install --user pdfminer.six` で入れる。popplerを入れられない環境向け)。どちらも無ければ `FAIL` になる |
+| `pdftotext`(popplerかXpdf) | PDFから本文を取り出す | [pdfminer.six](https://github.com/pdfminer/pdfminer.six) が入っていれば、代わりにそれで取り出す(スクリプトを動かすPythonに `python3 -m pip install --user pdfminer.six` で入れる。popplerを入れられない環境向け)。PATHにある `pdf2txt.py` でもよい(Windows以外)。pdftotextより遅く、大きなPDFは時間の上限で `FAIL` になることがある。どれも無ければ `FAIL` になる |
| `pdftoppm`(popplerかXpdf)と `tesseract` | 文字の層がない古いPDFをOCRにかける | そのPDFは `FAIL` になる |
| `tesseract` の言語データ `jpn` と `jpn_vert` | 日本語のスキャンPDFを、横書きも縦書きも読む(入っていれば自動で使う。環境変数 `IMOZURU_OCR_LANG` で `jpn+eng` のように指定もできる) | 英語だけで読む。日本語のPDFは読み取りの確信度が低いので `FAIL` になる |
| `yt-dlp` | YouTubeの字幕を取得する | 動画は `FAIL` になる |
diff --git a/skills/imozuru/SKILL.md b/skills/imozuru/SKILL.md
index 1f9b5ae..b4af7b8 100644
--- a/skills/imozuru/SKILL.md
+++ b/skills/imozuru/SKILL.md
@@ -153,7 +153,7 @@ map.md を下の書式で作り、**問い**と、答えるのに要る**論点*
原文を何十本も保存しただけでは読まれない(英語の PDF や1時間の字幕のまま)。かといって要約すると、早すぎる結論を招く。だから止めたら、**抜き書き**(Ellis の extracting)でページを作り、それを最初に渡す。
-1. `<topic_dir>/extracts.json` を書く。調査の論点ごとに節を立て、原文から**そのまま切り出した文**を並べる(ファイル・行・必要なら `end`)。英語には `ja` に訳を添える(訳だと分かる印がページに付く)。印(〔本人〕自動字幕 など)は `mark` に。元のページへのリンクは、map.md の「原文(sources/)」の表の「元の URL」から、表に無ければ取得の記録(fetch-log.jsonl)から自動で付く(http(s) の完全な URL だけ)。どちらにも無い原文に付けたいときだけ `url` に書く。2段組の PDF のように左右の段が1行に混ざる所は、抜き書きを「…」で区切ると区切りごとに順に照合される(省いたことはページにも「…」で見える)。食い違いは `disagreements` に並べるだけで、どれが正しいかは書かない。届かなかったものは `unreached` に。形の手本はリポジトリの `examples/demo/extracts.json`
+1. `<topic_dir>/extracts.json` を書く。調査の論点ごとに節を立て、原文から**そのまま切り出した文**を並べる(ファイル・行・必要なら `end`)。英語には `ja` に訳を添える(訳だと分かる印がページに付く)。印(〔本人〕自動字幕 など)は `mark` に。元のページへのリンクは、map.md の「原文(sources/)」の表の「元の URL」から、表に無ければ取得の記録(fetch-log.jsonl)から自動で付く(http(s) の完全な URL だけ)。どちらにも無い原文に付けたいときだけ `url` に書く。2段組の PDF のように左右の段が1行に混ざる所は、抜き書きを「…」で区切ると区切りごとに順に照合される(省いたことはページにも「…」で見える)。数で始まる所を写すとき、原文でその直前に負号(-・−・-・–)があれば負号ごと写す。数で始まる箇条書きの項目も「- 」ごと写す(負号と見分けられないので、落とすと照合で止まる)。食い違いは `disagreements` に並べるだけで、どれが正しいかは書かない。届かなかったものは `unreached` に。形の手本はリポジトリの `examples/demo/extracts.json`
形は report.py の冒頭と同じ(`?` は省いてよい)。
```
{"title", "question", "stopped",
diff --git a/skills/imozuru/scripts/dashboard.py b/skills/imozuru/scripts/dashboard.py
index 8d90a3b..5871d2f 100644
--- a/skills/imozuru/scripts/dashboard.py
+++ b/skills/imozuru/scripts/dashboard.py
@@ -28,6 +28,7 @@ import shutil
import sys
import tempfile
from collections import Counter
+from datetime import datetime
from pathlib import Path
from urllib.parse import urlsplit
@@ -127,12 +128,15 @@ def read(path: Path) -> str:
def load_jsonl(path: Path) -> list[dict]:
+ """1行1件の記録を読む。読めない行と、オブジェクトでない行は飛ばす(1行の崩れで一覧ごと落とさない)"""
rows = []
for line in read(path).splitlines():
try:
- rows.append(json.loads(line))
+ row = json.loads(line)
except ValueError:
continue
+ if isinstance(row, dict):
+ rows.append(row)
return rows
@@ -467,9 +471,12 @@ def serve(root: Path, runs: list[dict], port: int) -> int:
def started_at(d: Path) -> float:
- """調査を始めた時刻の目安。sources/ で一番古いファイル(最初に保存した原文)、無ければ map.md・log.md の古いほう。
- 記録(log.md・jsonl)には時刻が無いので、ファイルの時刻を使う。リンクはたどらない。何も無ければ 0"""
- times = []
+ """調査を始めた時刻の目安。取得の記録(fetch-log.jsonl)に時刻があれば一番早いもの。
+ 2.2.0 より前の記録には時刻が無いので、sources/ で一番古いファイル(最初に保存した原文)、無ければ map.md・log.md の古いほう。
+ ファイルの時刻は clone やコピーで変わるので、記録の時刻を先に使う。リンクはたどらない。何も無ければ 0"""
+ times = [t for f in load_jsonl(d / "fetch-log.jsonl") if (t := _epoch(f.get("at"))) is not None]
+ if times:
+ return min(times)
try:
with os.scandir(d / "sources") as it:
times = [e.stat(follow_symlinks=False).st_mtime for e in it if e.is_file(follow_symlinks=False)]
@@ -486,6 +493,16 @@ def started_at(d: Path) -> float:
return min(times, default=0.0)
+def _epoch(at: object) -> float | None:
+ """取得の記録の時刻(ISO 8601)を秒にする。読めなければ None"""
+ if not isinstance(at, str):
+ return None
+ try:
+ return datetime.fromisoformat(at).timestamp()
+ except ValueError:
+ return None
+
+
def collect(root: Path, runs: list[dict]) -> list[dict]:
topics = [topic_info(d, runs) for d in sorted(root.iterdir())
if not d.is_symlink() and d.is_dir() and SLUG.fullmatch(d.name)]
diff --git a/skills/imozuru/scripts/digest.py b/skills/imozuru/scripts/digest.py
index 7beeb02..ce33795 100644
--- a/skills/imozuru/scripts/digest.py
+++ b/skills/imozuru/scripts/digest.py
@@ -392,6 +392,8 @@ def build(topic: Path, check_only: bool) -> int:
if bad:
print("根拠の照合に通らない文がある(根拠が無いか、引用が原文と合わない):")
print("\n".join(" " + b for b in bad))
+ if any("原文に見つからない引用" in b for b in bad):
+ print(report.MINUS_HINT)
return 1
print(f"照合 OK: 解説の文がすべて原文の引用を持つ・検索の記録 {len(records)}本")
if check_only:
diff --git a/skills/imozuru/scripts/fetch.py b/skills/imozuru/scripts/fetch.py
index 67d9ab8..fa3439e 100755
--- a/skills/imozuru/scripts/fetch.py
+++ b/skills/imozuru/scripts/fetch.py
@@ -35,6 +35,7 @@ import tempfile
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
+from datetime import datetime, timezone
from html.parser import HTMLParser
from pathlib import Path
from xml.parsers import expat
@@ -498,12 +499,17 @@ def pdf_text_command(pdf: Path, out: Path) -> list[str] | None:
# 子の処理の作業フォルダは、取ってきたファイルの無いこのスクリプトの置き場にする。
# python -c は作業フォルダから先に読み込むので、ダウンロードの隣で動かさない
return [sys.executable, "-c", PDFMINER, str(pdf), str(out)]
- # pipx などで、コマンドだけ PATH にある。Windows は .py を直接は動かせないので使わない
- if os.name != "nt" and not missing("pdf2txt.py"):
+ if has_pdf2txt():
return ["pdf2txt.py", "-o", str(out), str(pdf)]
return None
+def has_pdf2txt() -> bool:
+ """pdfminer.six のコマンド pdf2txt.py を使えるか。pipx などで、コマンドだけ PATH にあることがある。
+ Windows は .py を直接は動かせないので使わない"""
+ return os.name != "nt" and not missing("pdf2txt.py")
+
+
def pdf_to_text(pdf: Path) -> str:
"""PDF を、行番号で原文を指せる文字にする。pdftotext なら段組みを保つ -layout を使う。"""
out = pdf.with_suffix(".txt")
@@ -1234,7 +1240,7 @@ def verify_and_save(name: str, text: str, saved: Path, kept: Path, destination:
reason = f"壁に当たった({wall})" if wall else f"本文が短すぎる({len(text)}文字)"
# PDF の文字起こしに要るコマンドが欠けていたなら、短い理由はたいていそれ
lacking = missing("pdftotext", "pdftoppm", "tesseract") if saved.suffix == ".pdf" else []
- if "pdftotext" in lacking and pdf_text_command(saved, kept) is not None:
+ if "pdftotext" in lacking and (has_pdfminer() or has_pdf2txt()):
lacking.remove("pdftotext") # 代わりの pdfminer.six で文字の層は読んだ。足りないのは OCR の道具
if lacking:
reason += f"。{'・'.join(lacking)} が無い"
@@ -1284,7 +1290,8 @@ def record_fetch(sources: Path, name: str, url: str, printed: str) -> None:
if not lines:
return
parts = lines[-1].split("\t")
- entry = {"url": url, "name": name, "status": parts[0]}
+ # 時刻はダッシュボードが同じ日の調査を始めた順に並べるのに使う。ファイルの時刻は clone やコピーで変わる
+ entry = {"url": url, "name": name, "status": parts[0], "at": datetime.now(timezone.utc).isoformat(timespec="seconds")}
if parts[0] == "OK" and len(parts) > 2:
entry["file"] = Path(parts[2]).name
elif len(parts) > 2:
diff --git a/skills/imozuru/scripts/report.py b/skills/imozuru/scripts/report.py
index ffda4a3..9b69c22 100644
--- a/skills/imozuru/scripts/report.py
+++ b/skills/imozuru/scripts/report.py
@@ -42,15 +42,22 @@ OLD_STATUS = {"付いた": "根拠あり", "一部だけ": "一部のみ", "付
# 前後に見せる行数。抜き書きがどんな流れの中にあったかを、ページの中で開いて確かめられるように。
CONTEXT_LINES = 6
-# 負号として扱う字(PDF は U+2212 を使うことがある)と、その後ろで符号つきの数になりうる字
-MINUS = ("-", "\u2212")
-SIGNED_START = "01234567890123456789."
+# 負号として扱う字。PDF は U+2212 を、和文は全角の U+FF0D を、組版された英文は en dash(U+2013)を使うことがある
+MINUS = ("-", "\u2212", "\uff0d", "\u2013")
+# 符号つきの数の始まり。「.」だけでは数にしない(「- .NET 8」の「.NET」を負号の後ろと見なさない)
+SIGNED_NUMBER = re.compile(r"[..]?\d")
+# 負号の直前にこの字があれば、語の中のハイフン(COVID-19・18-65・行末で切った「period-」)として扱う。
+# 和文の「気温は-5度」を通さないよう、仮名や漢字は含めない
+WORD_CHAR = re.compile(r"[A-Za-z0-90-9A-Za-z]")
+# 照合に落ちたときの案内。行番号のずれと思って行を直しても通らないので、負号の決まりをここで知らせる
+MINUS_HINT = ("数で始まる抜き書きは、原文でその直前に負号(-・−・-・–)があれば負号ごと写す。"
+ "数で始まる箇条書きの項目も「- 」ごと写す(負号と見分けられないため)")
def norm(s: str) -> str:
"""照合用に空白・改行・箇条書きの印をそろえる。文字そのものは変えない。
- 数字か小数点が続く行頭の「- 」は負号かもしれないので残す(#19)"""
- s = re.sub(r"(?m)^\s*(?:\*|-(?!\s*[\d.]))\s+", " ", s)
+ 数が続く行頭の「- 」は負号かもしれないので残す(#19)"""
+ s = re.sub(r"(?m)^\s*(?:\*|-(?!\s*[..]?\d))\s+", " ", s)
return re.sub(r"\s+", " ", s).strip()
@@ -105,11 +112,12 @@ def verify(src_dir: Path, q: dict) -> tuple[bool, list[str], int, int]:
def _in_order(pieces: list[str], region: str) -> bool:
"""区切りがどれも、前の区切りより後ろに region の中で現れるか。
- 数字か小数点で始まる区切りは、負号の直後の位置では数えない(「- 5 mg」の中の「5 mg」を通さない・#19)"""
+ 数で始まる区切りは、負号の直後の位置では数えない(「- 5 mg」の中の「5 mg」を通さない・#19)"""
+ signed = [bool(SIGNED_NUMBER.match(p)) for p in pieces]
pos = 0
- for piece in pieces:
+ for piece, number in zip(pieces, signed):
at = region.find(piece, pos)
- while at >= 0 and piece[0] in SIGNED_START and region[:at].rstrip().endswith(MINUS):
+ while at >= 0 and number and _after_minus(region, at):
at = region.find(piece, at + 1)
if at < 0:
return False
@@ -117,6 +125,12 @@ def _in_order(pieces: list[str], region: str) -> bool:
return True
+def _after_minus(region: str, at: int) -> bool:
+ """region の at の直前(空白を除く)が負号か。英数字の直後のハイフンは語の一部なので負号にしない"""
+ head = region[:at].rstrip()
+ return head.endswith(MINUS) and not WORD_CHAR.fullmatch(head[-2:-1] or " ")
+
+
def esc(s: str) -> str:
return html.escape(s, quote=True)
@@ -351,6 +365,7 @@ def main() -> int:
if bad:
print("原文に見つからない抜き書きがある(言い換えか、行番号のずれ):")
print("\n".join(" " + b for b in bad))
+ print(MINUS_HINT)
return 1
total = sum(len(g.get("quotes", [])) for _, g in groups)
print(f"照合 OK: 抜き書き {total} 件がすべて原文のとおり")
diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py
index 838d89b..94d1c28 100644
--- a/tests/test_dashboard.py
+++ b/tests/test_dashboard.py
@@ -300,6 +300,13 @@ class DashboardTests(unittest.TestCase):
os.utime(t / "sources" / name, (stamp, stamp))
order = [t["slug"] for t in dash.collect(self.root, []) if t["date"] == "2026-10-28"]
self.assertEqual(order, ["a-late", "m-noon", "z-early"])
+ # 取得の記録に時刻があれば、ファイルの時刻より先に使う(clone やコピーでファイルの時刻は変わる)
+ log = self.root / "z-early" / "fetch-log.jsonl"
+ # base は 2027-01-15T08:00Z。記録の時刻 base+22時間は a-late の原文(base+20時間)より後
+ log.write_text('{"status": "OK", "at": "2027-01-16T06:00:00+00:00"}\n["not a row"]\n'
+ '{"status": "FAIL", "at": "broken"}\n', encoding="utf-8")
+ order = [t["slug"] for t in dash.collect(self.root, []) if t["date"] == "2026-10-28"]
+ self.assertEqual(order, ["z-early", "a-late", "m-noon"])
def test_topic_without_records_is_marked_not_zero(self):
t = self.collect()["empty-topic"]
diff --git a/tests/test_digest.py b/tests/test_digest.py
index ec9b9e3..854e1a8 100644
--- a/tests/test_digest.py
+++ b/tests/test_digest.py
@@ -7,6 +7,7 @@ import json
import sys
import tempfile
import unittest
+from datetime import datetime
from pathlib import Path
from unittest.mock import patch
@@ -259,6 +260,7 @@ class FetchLogTests(unittest.TestCase):
rows = [json.loads(l) for l in (sources.parent / "fetch-log.jsonl").read_text().splitlines()]
self.assertEqual(rows[0]["status"], "FAIL")
self.assertEqual(rows[0]["url"], "file:///etc/passwd")
+ self.assertIsNotNone(datetime.fromisoformat(rows[0]["at"]).tzinfo) # 並べ替えに使う時刻
self.assertEqual(list(sources.iterdir()), [])
def test_fetch_log_is_skipped_outside_a_sources_folder(self):
diff --git a/tests/test_file_boundaries.py b/tests/test_file_boundaries.py
index 1a7fe57..3f20771 100644
--- a/tests/test_file_boundaries.py
+++ b/tests/test_file_boundaries.py
@@ -149,6 +149,37 @@ class FileBoundaryTests(unittest.TestCase):
q = {"file": "reasons.md", "line": 3, "end": 4, "text": text}
self.assertEqual(report.verify(self.sources, q)[0], expected)
+ def test_report_accepts_numbers_after_hyphens_inside_words(self):
+ """英数字の直後のハイフンは語の一部。その後ろから写した抜き書きは通す(2.1.0 で通っていた)。
+ 2段組の PDF では、行末で切った語「period-」の直後に左の段の数が来る"""
+ (self.sources / "words.txt").write_text(
+ "COVID-19 patients were enrolled.\nAged 18-65 years.\n"
+ "over a 40-day period- 0% to 30% of runs\n", encoding="utf-8")
+ for line, text in ((1, "19 patients were enrolled."), (2, "65 years."), (3, "0% to 30% of runs")):
+ with self.subTest(text=text):
+ self.assertTrue(report.verify(self.sources, {"file": "words.txt", "line": line, "text": text})[0])
+
+ def test_report_minus_needs_a_number_after_it(self):
+ """「.」だけでは数にしない。「- .NET 8」は箇条書きの印を落として写しても通し、「- .5 mg」は通さない。"""
+ (self.sources / "dotnet.md").write_text("# Notes\n\n- .NET 8 adds native AOT\n- .5 mg daily\n",
+ encoding="utf-8")
+ cases = {(3, ".NET 8 adds native AOT"): True, (4, ".5 mg daily"): False, (4, "- .5 mg daily"): True}
+ for (line, text), expected in cases.items():
+ with self.subTest(text=text):
+ q = {"file": "dotnet.md", "line": line, "text": text}
+ self.assertEqual(report.verify(self.sources, q)[0], expected)
+
+ def test_report_keeps_fullwidth_minus_and_en_dash(self):
+ """全角の負号と en dash も負号として扱う。和文の「は-5」は語の中のハイフンにしない。"""
+ (self.sources / "signs.txt").write_text(
+ "気温は-5度だった。\nChange was –3 points.\nSeasons 2019–2020 ended.\n", encoding="utf-8")
+ cases = {(1, "5度だった。"): False, (1, "気温は-5度だった。"): True,
+ (2, "3 points."): False, (3, "2020 ended."): True}
+ for (line, text), expected in cases.items():
+ with self.subTest(text=text):
+ q = {"file": "signs.txt", "line": line, "text": text}
+ self.assertEqual(report.verify(self.sources, q)[0], expected)
+
def test_failed_report_keeps_prior_content(self):
(self.sources / "paper.md").write_text("Original sentence", encoding="utf-8")
data = {"title": "Test", "question": "Q", "stopped": "Done", "claims": [
diff --git a/tests/test_portability.py b/tests/test_portability.py
index 3a47a84..e5c847b 100644
--- a/tests/test_portability.py
+++ b/tests/test_portability.py
@@ -126,7 +126,14 @@ class PdfToTextTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
fetch.has_pdfminer.cache_clear()
self.addCleanup(fetch.has_pdfminer.cache_clear)
- with patch.dict(os.environ, {"PYTHONPATH": tmp}):
+ # 本物の pdfminer.six が --user に入っている機械でも「無い」側を確かめられるよう、ユーザーの置き場を見せない。
+ # 仮想環境や Python 本体の側に入っているときは隠せないので、この試験を飛ばす
+ env = {"PYTHONPATH": tmp, "PYTHONNOUSERSITE": "1"}
+ with patch.dict(os.environ, env):
+ if fetch.has_pdfminer():
+ self.skipTest("pdfminer.six が Python 本体の側に入っている")
+ fetch.has_pdfminer.cache_clear()
+ with patch.dict(os.environ, env):
self.assertFalse(fetch.has_pdfminer())
fake = Path(tmp) / "pdfminer"
fake.mkdir()