m1macbookAir にpython 3.11をインストール

pip install browser-use

を実行したら

ERROR: Ignored the following versions that require a different python version: 0.1.0 Requires-Python >=3.11; 0.1.1 Requires-Python >=3.11; 0.1.10 Requires-Python >=3.11; 0.1.11 Requires-Python >=3.11; 0.1.12 Requires-Python >=3.11; 0.1.13 Requires-Python >=3.11; 0.1.14 Requires-Python >=3.11; 0.1.15 Requires-Python >=3.11; 0.1.16 Requires-Python >=3.11; 0.1.17 Requires-Python >=3.11; 0.1.18 Requires-Python >=3.11; 0.1.19 Requires-Python >=3.11; 0.1.20 Requires-Python >=3.11; 0.1.21 Requires-Python >=3.11; 0.1.22 Requires-Python >=3.11; 0.1.23 Requires-Python >=3.11; 0.1.3 Requires-Python >=3.11; 0.1.4 Requires-Python >=3.11; 0.1.5 Requires-Python >=3.11; 0.1.6 Requires-Python >=3.11; 0.1.7 Requires-Python >=3.11; 0.1.8 Requires-Python >=3.11
ERROR: Could not find a version that satisfies the requirement browser-use (from versions: none)
ERROR: No matching distribution found for browser-use

となった

python3 --version
Python 3.10.6

これが原因なので
バージョンを変える

過去ログを見たら
とりあえず python 3.10 を入れる

今の環境を python -V
で調べたら3.8.12だった

pyenv install 3.10.6

で参考サイトと同じバージョンをインストール

pyenv global 3.10.6

で使用するバージョンを変更

となっていたので
Pyenvを使い更新

pyenv install 3.11

しかし

BUILD FAILED (OS X 15.2 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/db/tkl5w9dd3kn3h53ctyl4s6180000gn/T/python-build.20250115025749.25266
Results logged to /var/folders/db/tkl5w9dd3kn3h53ctyl4s6180000gn/T/python-build.20250115025749.25266.log

Last 10 log lines:
      __locale_localeconv in _localemodule.o
      __locale_localeconv in _localemodule.o
      __locale_localeconv in _localemodule.o
  "_libintl_textdomain", referenced from:
      __locale_textdomain in _localemodule.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Programs/_freeze_module] Error 1
make: *** Waiting for unfinished jobs....
2 warnings generated.

となる

brew update

しても変わらない

chatGPTでは

brew install openssl readline xz zlib gettext

っていうけど

==> Downloading https://formulae.brew.sh/api/formula.jws.json

==> Downloading https://formulae.brew.sh/api/cask.jws.json

openssl@3 3.3.1 is already installed but outdated (so it will be upgraded).
readline  is already installed but outdated (so it will be upgraded).
xz 5.6.2 is already installed but outdated (so it will be upgraded).
gettext 0.22.5 is already installed but outdated (so it will be upgraded).
Error: Cannot install under Rosetta 2 in ARM default prefix (/opt/homebrew)!
To rerun under ARM use:
    arch -arm64 brew install ...
To install under x86_64, install Homebrew into /usr/local.

となる

このためエラーログで検索する

python-build: use zlib from xcode sdk

BUILD FAILED (OS X 15.2 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/db/tkl5w9dd3kn3h53ctyl4s6180000gn/T/python-build.20250115030607.37878
Results logged to /var/folders/db/tkl5w9dd3kn3h53ctyl4s6180000gn/T/python-build.20250115030607.37878.log

Last 10 log lines:
      __locale_localeconv in _localemodule.o
      __locale_localeconv in _localemodule.o
      __locale_localeconv in _localemodule.o
  "_libintl_textdomain", referenced from:
      __locale_textdomain in _localemodule.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Programs/_freeze_module] Error 1
make: *** Waiting for unfinished jobs....
2 warnings generated.

で検索

M1 Mac にpyenvで環境構築してみたらBUILD FAILEDと怒られた件
を参考にしたけど
だめ

BUILD FAILED (OS X 15.2 using python-build 20180424)

で検索

pyenvでインストール時に「BUILD FAILED (OS X 10.15.7 using python-build 20180424)」が発生した場合の対処法
を参考に

arch -arm64 brew install zlib

でインストール

これでもダメなので

M2 Mac】pyenv環境構築でハマった話 (BUILD FAILED)
を参考に

arch -arm64 brew install readline openssl zlib xz

これでもだめ

なぜかx86_64向けにビルドしようとしていて,ホストもx86_64になっているため


PYTHON_CONFIGURE_OPTS="--host=arm-apple-darwin --build=arm-apple-darwin" \
CFLAGS="-I$(brew --prefix readline)/include -I$(brew --prefix openssl)/include -I$(brew --prefix zlib)/include -I$(brew --prefix xz)/include -arch arm64" \
LDFLAGS="-L$(brew --prefix readline)/lib -L$(brew --prefix openssl)/lib -L$(brew --prefix zlib)/lib -L$(brew --prefix xz)/lib -arch arm64" \
pyenv install -v 3.11.0

というように

* PYTHON_CONFIGURE_OPTS: ホストとビルドシステムをarm-apple-darwin に明示。
* CFLAGS とLDFLAGS : 必要なライブラリのパスを正確に指定し、-arch arm64 を追加。

とすれば
インストール成功

あとは

pyenv global 3.11.0

で設定して

 python -V          
Python 3.11.0

となれば成功

Neo4j の起動

Neo4j の起動

pythonでneo4j を使えるようにする

Llama 3.2とNeo4jでローカルGraphRAG環境を構築

これをやる場合
Neo4jのCypherクエリ言語を拡張するライブラリapoc-coreを使用する

Dockerコンテナを利用したNeo4jの環境構築とAPOCのインストール手順
によれば
コンテナで起動したNeo4jにはAPOCのバイナリが含まれていないため、手動でインストールする必要がある

APOC (Awesome Procedures On Cypher) は、Neo4jにおける拡張機能の一つである。
データ操作、外部データの取り込み、ランダムグラフ生成など、Neo4jの基本機能を拡張するプロシージャを提供する。

製品の標準機能として取り込まれた拡張機能も多々あるようで、
とりあえずコアのAPOC入れておいたほうがいい、ということらしい

docker exec -it neo4j-neo4j-1 neo4j --version

を実行したけど

Error response from daemon: No such container: neo4j-neo4j-1

となった

コンテナが起動していないと意味がない

まずはneo4jを起動する

Docker-compose を使う方法を採用

対応ディレクトリが必要なので

mkdir -p ./data ./logs ./conf ./plugins
chmod 755 ./data ./logs ./conf ./plugins

で作成する

次に

touch docker-compose.yml

でファイルを作成


dservices:
  neo4j:
    image: neo4j:latest
    ports:
      - "7474:7474"
      - "7687:7687"
    environment:
      NEO4J_AUTH: "neo4j/[8文字以上のパスワード]"
      NEO4J_apoc_export_file_enabled: "true"
      NEO4J_apoc_import_file_enabled: "true"
      NEO4J_apoc_import_file_use__neo4j__config: "true"
      NEO4J_dbms_security_procedures_unrestricted: "apoc.*"
    ulimits:
      nofile:
        soft: 40000
        hard: 40000
    volumes:
      - ./data:/data
      - ./logs:/logs
      - ./conf:/conf
      - ./plugins:/plugins

として保存

なお
neo4j/ は必須で、
NEO4J_AUTH の形式は常に ユーザー名/パスワード
となっている
なので通常はパスワードを変更する

docker compose up -d

を実行したが

validating /Users/snowpool/aw10s/ne4j_pg/docker-compose.yml: (root) Additional property dservices is not allowed

となる

GPTで調べると

ocker-compose.yml ファイルで
トップレベルのキーとして dservices が使用されているためです。
Docker Compose の標準では、
トップレベルのキーは services である必要があります。

となるため
コードを修正

最初の

dservices:

services:

へ変更し保存

docker compose up -d

を実行すれば

[+] Running 2/2
 ✔ Network ne4j_pg_default    Created                                      0.0s 
 ✔ Container ne4j_pg-neo4j-1  Started                                      0.2s 

となる

これで
http://localhost:7474
へアクセスし
管理画面が表示されればOK

管理画面には
docker-compose.yamlで設定したID「neo4j」とそのパスワードでログインする

ログインしたらテスト

CREATE (p:Person {name: "Alice", age: 30})-[:KNOWS]->(p2:Person {name: "Bob", age: 25})


Cypherクエリを実行し、ノードとリレーションシップを作成

MATCH (n) RETURN n

を実行すると
登録したデータの確認が画像で表示される

データ永続化のテストのため

docker compose down

でコンテナを停止

コンテナを再起動するので

docker compose up -d

これで再度

MATCH (n) RETURN n

を実行して表示されれば問題なし

次に
APOCバイナリのインストール

これには dockerコンテナの名前が必要なので

docker ps

を実行しコンテナ名を調べる

CONTAINER ID   IMAGE          COMMAND                   CREATED         STATUS         PORTS                                                      NAMES
cc1a5da764cf   neo4j:latest   "tini -g -- /startup…"   7 minutes ago   Up 7 minutes   0.0.0.0:7474->7474/tcp, 7473/tcp, 0.0.0.0:7687->7687/tcp   ne4j_pg-neo4j-1

という結果になったので
コンテナ名は ne4j_pg-neo4j-1
ということがわかる

次にNeo4j のバージョン表示

docker exec -it ne4j_pg-neo4j-1 neo4j --version

を実行すれば

5.26.0

とバージョンが表示される

Neo4jのバージョンに対応するAPOCをGitHubリリースページからダウンロード

今回は
apoc-5.26.0-core.jar
をダウンロード

これを plugins ディレクトリに配置する

mv ~/Downloads/apoc-5.26.0-core.jar plugins 

次にコンテナ再起動

docker compose down
docker compose up -d

次に
http://localhost:7474
へアクセス

CALL apoc.help('apoc')

を実行し
APOCが利用可能になっていることを確認

Zenn CLIで記事・本を管理

実行環境
M1 MacbookAir 16GB

Zenn CLIで記事・本を管理する方法を参考にする前に

Zenn CLIをインストールする
を参考にインストールする

その前に
GitHubリポジトリと連携が必要

GitHubリポジトリでZennのコンテンツを管理する
を参考に行う

まずgithubで
好きな名前のリポジトリを作成する
zenn_article
とした

公開設定は public でOK

ライセンスはとりあえずMItにしておく

これで
Create repository
をクリック

これを
Zennのダッシュボードから連携する

リポジトリ連携の時に
Only select repositories
をクリックし
作成したリポジトリを指定する

これで同期するブランチ名を確認できればOK

次に
ローカルでのファイルの作成や、markdownのプレビューにはZenn CLIを使うので
これを設定する

Zenn CLIを使うにはNode.js 14以上が必要

git clone https://github.com/Snowpooll/zenn_article.git


リポジトリを clone する

cd zenn_article 

で移動し

npm init --yes
npm install zenn-cli

でインストール

Zenn用のセットアップのため

npx zenn init

実行すると

  🎉  Done!
  早速コンテンツを作成しましょう

  👇  新しい記事を作成する
  $ npx zenn new:article

  👇  新しい本を作成する
  $ npx zenn new:book

  👇  投稿をプレビューする
  $ npx zenn preview

となる

とりあえずここまでできたら
Zenn CLIで記事・本を管理する方法
を参考に記事を書いていく

Chatgpt で
zenn で markdown で記事を記述したいので以下の文章を修正してほしい
publication_name: “singularity” をヘッダーに追加してほしい

とした後にブログ記事をコピペ

これで記事の構成ができる

あとは記事を作成するので

npx zenn new:article

で記事を作成

これでベースとなるものが作成される

---
title: ""
emoji: "🔥"
type: "tech" # tech: 技術記事 / idea: アイデア
topics: []
published: false
---

これにコピペしていく

今回は

---
title: "現在地の天気情報の取得その2"
emoji: "☀️"
type: "tech" # tech: 技術記事
topics: ["天気", "Python", "OpenWeatherMap"]
published: true
publication_name: "singularity"
---

# 現在地の天気情報の取得その2

## Pythonで天気情報を取得する方法

以下はPythonを使って、郵便番号とAPIキーで天気情報を取得するコード例です。

```python
import requests
import json
from pprint import pprint

# OpenWeatherMap APIのURL
url = "https://api.openweathermap.org/data/2.5/weather?zip={zip_place}&units=metric&appid={API_key}"

# 郵便番号とAPIキーを指定
url = url.format(zip_place="郵便番号,JP", API_key="APIキー")

# APIからデータを取得
jsondata = requests.get(url).json()
pprint(jsondata)

# 天気情報を出力
print("天気:", jsondata["weather"][0]["main"])
print("天気詳細:", jsondata["weather"][0]["description"])
print("都市名:", jsondata["name"])
print("気温:", jsondata["main"]["temp"])
print("体感気温:", jsondata["main"]["feels_like"])
print("最低気温:", jsondata["main"]["temp_min"])
print("最高気温:", jsondata["main"]["temp_max"])
print("気圧:", jsondata["main"]["pressure"])
print("湿度:", jsondata["main"]["humidity"])
print("風速:", jsondata["wind"]["speed"])
print("風の方角:", jsondata["wind"]["deg"])
```

### 実行結果
```plaintext
{'base': 'stations',
 'clouds': {'all': 0},
 'cod': 200,
 'coord': {'lat': 緯度, 'lon': 経度},
 'main': {'feels_like': 4.12,
          'humidity': 60,
          'pressure': 1021,
          'temp': 6.65,
          'temp_max': 6.65,
          'temp_min': 6.65},
 'name': 'Kawai',
 'weather': [{'description': 'clear sky', 'main': 'Clear'}],
 'wind': {'deg': 288, 'speed': 3.58}}
天気: Clear
天気詳細: clear sky
都市名: Kawai
気温: 6.65
体感気温: 4.12
最低気温: 6.65
最高気温: 6.65
気圧: 1021
湿度: 60
風速: 3.58
風の方角: 288
```

## 日本語での天気情報取得

英語の天気情報を日本語に変換するには、以下の辞書を用いてマッピングします。

### 英語から日本語への天気翻訳辞書
```python
weather_translation = {
    "Clear": "晴れ",
    "Clouds": "曇り",
    "Rain": "雨",
    "Snow": "雪",
    "Thunderstorm": "雷雨",
    "Drizzle": "霧雨",
    "Mist": "霧",
    "Fog": "濃霧"
}

# APIから取得した天気を翻訳する
weather_english = jsondata["weather"][0]["main"]
weather_japanese = weather_translation.get(weather_english, "不明")  # 辞書にない場合は「不明」と表示

print("天気(日本語):", weather_japanese)
```

これにより、APIから取得した天気情報を日本語で表示できます。

## 天気情報を詳細に取得する方法

緯度経度を使用して、一日の最高気温と最低気温を取得するには以下のコードを使用します。
```python
import requests
from datetime import datetime

# OpenWeather APIのURLとパラメータ
url = "https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude=hourly,minutely&units=metric&appid={API_key}"
latitude = "緯度"
longitude = "経度"
API_key = "YOUR_API_KEY"

# APIリクエスト
url = url.format(lat=latitude, lon=longitude, API_key=API_key)
response = requests.get(url)
jsondata = response.json()

# 今日の最高気温と最低気温
today = datetime.now().date()
for daily in jsondata["daily"]:
    date = datetime.fromtimestamp(daily["dt"]).date()
    if date == today:
        print("今日の最高気温:", daily["temp"]["max"], "度")
        print("今日の最低気温:", daily["temp"]["min"], "度")
        break
```

## 今後の展望

- 天気情報を音声に変換して通知
- 現在地の天気や移動予定地の天気を自動で取得・表示

とした

これで保存し

npx zenn preview

を実行
http://localhost:8000
をブラウザでひらけば記事のプレビューが見れる

これで問題なければ記事の公開

git add .
git commit -m "記事を追加: 現在地の天気情報の取得その2"
git push origin main

しかし https認証が廃止されているので
Sshでアップしないとだめ

git remote -v

で確認すると

origin	https://github.com/Snowpooll/zenn_article.git (fetch)
origin	https://github.com/Snowpooll/zenn_article.git (push)

これを

git remote set-url origin git@github.com:Snowpooll/zenn_article.git

でSSH形式のリモートURLに変更

git remote -v

で確認できる

origin	git@github.com:Snowpooll/zenn_article.git (fetch)
origin	git@github.com:Snowpooll/zenn_article.git (push)

あとは

git push origin main

でsshキーのパスワードを入れればOK

Neo4jのインストール

Neo4jのインストール

https://neo4j.com/docs/getting-started/whats-neo4j/

3種類あるようなので
neo4jの デスクトップ、インストールタイプ、docker での必要スペックをまとめました
M1MacbookAir 16GBだと動かせそうなのは docker

これで動かすようにする

Neo4j の学習環境を Docker で構築する
によれば
NEO4J_AUTH=none にすることで、認証なしに環境へログインができるようになる

とりあえずdocker がインストールされていないので
これを先に入れる

Docker Desktopのインストール
https://www.docker.com/products/docker-desktop/
へアクセス

Get started をクリック

Download Docker Desktop をマウスオーバーすると
Download for Mac Apple Silicon
が表示されるのでクリック

これでダウンロードされる

ダウンロード完了したらダブルクリックで
Applicationにdocker をドラッグする

これでアプリを起動すると

Docker Subscription Service Agreement
By selecting accept, you agree to the Subscription Service Agreement⁠, the Docker Data Processing Agreement⁠, and the Data Privacy Policy⁠.
Commercial use of Docker Desktop at a company of more than 250 employees OR more than $10 million in annual revenue requires a paid subscription (Pro, Team, or Business). See subscription details⁠

と表示されるので意味を調べる

Docker サブスクリプション サービス契約
[同意する] を選択すると、サブスクリプション サービス契約、Docker データ処理契約、およびデータ プライバシー ポリシーに同意したことになります。

従業員数が 250 人を超える企業、または年間収益が 1,000 万ドルを超える企業で Docker Desktop を商用利用するには、有料のサブスクリプション (Pro、Team、または Business) が必要です。サブスクリプションの詳細を参照⁠

とのこと

この日本語で検索したら
https://oopsoop.com/install-docker/
MacにDocker Desktopをインストールする手順
が出てきた

とりあえずサイトを参考に
Accept をクリックし

Use recommended settings (requires password)
のままにして
Finishをクリック

次に Sign In か Sign up の画面になるけど
アカウント登録をしなくてもDockerの基本的な機能は使える
とのことなのでSkip にした

次にターミナルで

docker -v                

でバージョンを確認したら

Docker version 27.3.1, build ce12230

となったので
まずはインストール成功

Neo4jのDockerイメージを確認

docker search neo4j
NAME                              DESCRIPTION                                      STARS     OFFICIAL
neo4j                             Neo4j is a highly scalable, robust native gr…   1290      [OK]
bitnami/neo4j                     Bitnami container image for Neo4j                13        
bitnamicharts/neo4j               Bitnami Helm chart for Neo4j                     0         
vulhub/neo4j                                                                       0         
ocelotsocialnetwork/neo4j                                                          0         
neo4j/neo4j-experimental          Experimental Neo4j Docker images                 10        
neo4j/neo4j-admin                 Neo4j database administration tool.              1         
neo4j/helm-charts-backup          This repo will hold the docker image used by…   0         
neo4j/neo4j-arm64-experimental    Experimental Neo4j images for the ARM64 arch…   5         
neo4j/helm-charts-reverse-proxy   this repo holds the docker image for neo4j r…   0         
neo4j/neo4j-ops-manager-server    Neo4j Ops Manager server application             0         
neo4j/neo4j-ops-manager-agent     Neo4j Ops Manager agent is to be deployed on…   0         
amd64/neo4j                       Neo4j is a highly scalable, robust native gr…   0         
neo4j/helm-charts-operations      Neo4j helm chart operations which allows you…   0         
phenompeople/neo4j                Neo4j is a highly scalable, robust native gr…   1         
frodenas/neo4j                    A Docker Image for Neo4j                         8         
rapydo/neo4j                                                                       0         
tpires/neo4j                      Neo4j is a highly scalable, robust (fully AC…   82        
c12e/neo4j                                                                         0         
arm64v8/neo4j                     Neo4j is a highly scalable, robust native gr…   0         
2045c6c4/neo4j                                                                     0         
trollin/neo4j                                                                      0         
harshit9398/neo4j                 Customized Neo4j image for importing data fr…   0         
statisticsnorway/neo4j                                                             0         
cluedin/neo4j         

0
となる

Dockerを用いたPythonとNeo4jの開発環境構築


Chat got では
Docker Hubに登録しておくと、公式イメージを簡単にダウンロードできる
とのことなので
先に登録をする

結局登録することになった
https://hub.docker.com/
へアクセス

しかし既に登録されていると出る
おそらく昔ドットインストールで dockerやった時に登録している

とりあえずこれで登録はできているので
次にdocker イメージの取得

しかし

   
docker pull neo4j 

を実行すると

   
Using default tag: latest
Cannot connect to the Docker daemon at unix:///Users/snowpool/.docker/run/docker.sock. Is the docker daemon running? 

となる

原因を調べたら
M1 Macでは、Docker Desktopを手動で起動する必要があるらしい

再度 Docker Desktop を起動し

   
docker pull neo4j 

を実行したら

   
Using default tag: latest
latest: Pulling from library/neo4j
b8bfdadce121: Download complete 
c783cffde723: Download complete 
f549d6f5d7d3: Download complete 
46120a0c7324: Download complete 
879a6187682f: Download complete 
4f4fb700ef54: Download complete 
Digest: sha256:411e532d5c9892e7c955b4e631da423af41ede6a683a0de02c93876b7509c2db
Status: Downloaded newer image for neo4j:latest
docker.io/library/neo4j:latest
 

となった

とりあえずイメージ取得はできたが起動でわからないことがあるので
GPTで調べる

docker compose コマンドで Neo4j を起動するのと
docker run –name neo4j \ -p 7474:7474 -p 7687:7687 \ -e NEO4J_AUTH=neo4j/testpassword \ -v $HOME/neo4j/data:/data \ neo4j で起動する この違いは?

`docker compose` コマンドと `docker run` コマンドを使った起動方法の違いを説明します。それぞれの方法には特徴やメリットがあり、使用シーンによって使い分けることができます。

### **1. `docker run` を使った起動**
#### **特徴**
– 単一のコンテナを直接起動するため、簡単で軽量。
– 起動コマンド内で全ての設定(ポートマッピング、環境変数、ボリュームなど)を指定します。

#### **メリット**
– **シンプル**: コマンド一つで起動でき、設定ファイルが不要。
– **素早くテスト可能**: 手早く試したい場合に便利。

#### **デメリット**
– **複雑な設定が困難**: 設定が多い場合、コマンドが煩雑になりやすい。
– **再利用性が低い**: 毎回設定を入力する必要があり、同じ設定で複数環境を管理するのは難しい。
– **スケーリングが難しい**: 他のサービスとの連携が必要な場合には不向き。

### **2. `docker compose` を使った起動**
#### **特徴**
– 複数のコンテナやサービスを `docker-compose.yml` という設定ファイルで一括管理します。
– ネットワーク設定や環境変数、ボリュームなどをファイルで定義します。

#### **例: `docker-compose.yml` ファイル**
“`yaml
version: ‘3.8’
services:
neo4j:
image: neo4j
container_name: neo4j
ports:
– “7474:7474”
– “7687:7687”
environment:
– NEO4J_AUTH=neo4j/testpassword
volumes:
– $HOME/neo4j/data:/data
“`

#### **起動コマンド**
“`bash
docker compose up -d
“`

#### **メリット**
– **設定の再利用が簡単**: `docker-compose.yml` ファイルを使い回して環境を再現可能。
– **複数サービスの管理**: 複数のコンテナ(例: Neo4jと関連するアプリケーション)をまとめて起動・停止できる。
– **環境の可搬性**: 設定ファイルを共有すれば、他の環境でも同じ構成で起動可能。
– **スケールしやすい**: 複数インスタンスを簡単に立ち上げたり、複雑なネットワーク設定を扱いやすい。

#### **デメリット**
– **初期設定が必要**: `docker-compose.yml` ファイルを作成する手間がある。
– **単体での試験にはやや過剰**: シンプルなコンテナ起動には不要な場合が多い。

### **具体的な使い分け**

| **シーン** | **`docker run`** | **`docker compose`** |
|————————————|—————————————————|————————————————|
| **シンプルなテストや実験** | 最適 | 過剰な場合がある |
| **複数サービスの起動(例: Neo4j + アプリ)** | 煩雑 | 非常に便利 |
| **設定を何度も再利用する場合** | 毎回コマンド入力が必要 | 設定ファイルで簡単に再利用 |
| **本番環境の準備や運用** | 管理が難しい | 環境構築や管理に最適 |
| **チーム開発や共有環境** | 他者への設定共有が困難 | 設定ファイルで簡単に共有可能 |

### **結論**
– **単純な用途**: 一回限りのテストや小規模な利用では `docker run` が簡単。
– **再利用性・管理性が重要**: チーム開発や本格的な運用では `docker compose` を使うのがおすすめ。

とりあえず次にpythonでneo4j を使えるようにする

Llama 3.2とNeo4jでローカルGraphRAG環境を構築

これをやる場合
Neo4jのCypherクエリ言語を拡張するライブラリapoc-coreを使用する

Dockerコンテナを利用したNeo4jの環境構築とAPOCのインストール手順
によれば
コンテナで起動したNeo4jにはAPOCのバイナリが含まれていないため、手動でインストールする必要がある

APOC (Awesome Procedures On Cypher) は、Neo4jにおける拡張機能の一つである。
データ操作、外部データの取り込み、ランダムグラフ生成など、Neo4jの基本機能を拡張するプロシージャを提供する。

製品の標準機能として取り込まれた拡張機能も多々あるようで、
とりあえずコアのAPOC入れておいたほうがいい、ということらしい

docker exec -it neo4j-neo4j-1 neo4j --version

を実行したけど

Error response from daemon: No such container: neo4j-neo4j-1

となった

コンテナが起動していないと意味がない

まずはneo4jを起動する

UnstructuredによるPDFからの画像抽出

UnstructuredによるPDFからの画像抽出
を参考に進める

pip install ‘unstructured[pdf] と
pip install unstructured[all-docs] の違いを調べた

違いはPDFのみか
全てのドキュメント形式(PDF、Word、Excel、HTMLなど)
ということ

これを使い画像を抽出し学習データを作るので
そのままデータ保存できるcolab で実行する

【Python】unstructuredを使って、 PDFファイル内の非構造データを抽出する
を参考に

!pip install unstructured[all-docs]

でインストール

実行後にセッションの再起動を求められる

ITパスポートの過去問のうち、令和6年度分の問題冊子を使うので
https://www3.jitec.ipa.go.jp/JitesCbt/html/openinfo/questions.html
から
問題をダウンロード

!mkdir data

でフォルダを作成し
ここへアップロード

import os
from unstructured.partition.pdf import partition_pdf

# 現在の作業ディレクトリを取得
current_dir = os.getcwd()

# 'data'フォルダのパスを設定
DATA_PAR_PATH = os.path.join(current_dir, 'data')

# 処理対象のPDFファイルのパスを設定
DATASET_PATH = os.path.join(DATA_PAR_PATH, '2024r06_ip_qs.pdf')

# 画像の出力先フォルダのパスを設定
OUTPUT_PATH = os.path.join(DATA_PAR_PATH, 'images')

# フォルダ確認(存在しない場合エラーになるのでアップロード確認用)
if not os.path.exists(DATA_PAR_PATH):
    raise FileNotFoundError(f"'data'フォルダが見つかりません。Google Colabに'2024r06_ip_qs.pdf'をアップロードしてください。")

if not os.path.exists(DATASET_PATH):
    raise FileNotFoundError(f"ファイル '2024r06_ip_qs.pdf' が'data'フォルダ内に存在しません。ファイルをアップロードしてください。")

# PDFファイル内のデータを分割する
raw_pdf_elements = partition_pdf(
    filename=DATASET_PATH,
    chunking_strategy='by_title',
    infer_table_structure=True,
    extract_images_in_pdf=True,
    extract_image_block_output_dir=OUTPUT_PATH
)

# 処理が成功したことを表示
print("PDFファイルの処理が完了しました。")
print(f"画像は以下のフォルダに保存されます: {OUTPUT_PATH}")

として実行したが

WARNING:pdfminer.pdfpage:The PDF <_io.BufferedReader name='/content/data/2024r06_ip_qs.pdf'> contains a metadata field indicating that it should not allow text extraction. Ignoring this field and proceeding. Use the check_extractable if you want to raise an error in this case
yolox_l0.05.onnx: 100%

 217M/217M [00:02<00:00, 149MB/s]
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pdf2image/pdf2image.py in pdfinfo_from_path(pdf_path, userpw, ownerpw, poppler_path, rawdates, timeout, first_page, last_page)
    580             env["LD_LIBRARY_PATH"] = poppler_path + ":" + env.get("LD_LIBRARY_PATH", "")
--> 581         proc = Popen(command, env=env, stdout=PIPE, stderr=PIPE)
    582 



15 frames

FileNotFoundError: [Errno 2] No such file or directory: 'pdfinfo'
During handling of the above exception, another exception occurred:

PDFInfoNotInstalledError                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pdf2image/pdf2image.py in pdfinfo_from_path(pdf_path, userpw, ownerpw, poppler_path, rawdates, timeout, first_page, last_page)
    605 
    606     except OSError:
--> 607         raise PDFInfoNotInstalledError(
    608             "Unable to get page count. Is poppler installed and in PATH?"
    609         )

PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH?

となってしまう

これは
pdf2imageパッケージが内部的に使用している
poppler-utilsがインストールされていないために発生

!apt-get update
!apt-get install -y poppler-utils

でインストール

再度実行する

このとき、非構造データは画像として分割され、OUTPUT_PATHで指定したディレクトリに入る

この非構造データを確認してみた結果

* 画像しか検出していない
* テーブルも画像として認識してほしい
* 画像を出力する必要がある
* わざわざ出力せずに、byte型で非構造データを保持したい
* 画像の端っこが見切れている
* 画像によって、見切れ具合は様々

上記の結果を踏まえて非構造データの抽出を工夫

しかし

WARNING:pdfminer.pdfpage:The PDF <_io.BufferedReader name='/content/data/2024r06_ip_qs.pdf'> contains a metadata field indicating that it should not allow text extraction. Ignoring this field and proceeding. Use the check_extractable if you want to raise an error in this case
yolox_l0.05.onnx: 100%

 217M/217M [00:01<00:00, 237MB/s]
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/unstructured_pytesseract/pytesseract.py in get_tesseract_version()
    450     try:
--> 451         output = subprocess.check_output(
    452             [tesseract_cmd, '--version'],



21 frames

FileNotFoundError: [Errno 2] No such file or directory: 'tesseract'
During handling of the above exception, another exception occurred:

TesseractNotFoundError                    Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/unstructured_pytesseract/pytesseract.py in get_tesseract_version()
    456         )
    457     except OSError:
--> 458         raise TesseractNotFoundError()
    459 
    460     raw_version = output.decode(DEFAULT_ENCODING)

TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.

これは
このエラーは、PDFの画像からテキストを抽出するために必要なOCRエンジン Tesseract がインストールされていないために発生しています。Google Colabではデフォルトで Tesseract がインストールされていないため

!apt-get update
!apt-get install -y tesseract-ocr
!apt-get install -y libtesseract-dev

でインストール

これで再度

import base64
import io
import os
from PIL import Image
from unstructured.partition.pdf import partition_pdf

# Google Colab環境用のパス設定
current_dir = os.getcwd()
DATA_PAR_PATH = os.path.join(current_dir, 'data')  # 'data'フォルダを利用
DATASET_PATH = os.path.join(DATA_PAR_PATH, '2024r06_ip_qs.pdf')

# 必要なフォルダやファイルの存在確認
if not os.path.exists(DATA_PAR_PATH):
    raise FileNotFoundError(f"'data'フォルダが存在しません。Google Colabに'2024r06_ip_qs.pdf'をアップロードしてください。")

if not os.path.exists(DATASET_PATH):
    raise FileNotFoundError(f"ファイル '2024r06_ip_qs.pdf' が 'data' フォルダ内に存在しません。アップロードしてください。")

# PDFファイル内のデータを分割する
raw_pdf_elements = partition_pdf(
    filename=DATASET_PATH,
    infer_table_structure=True,
    strategy='hi_res',
    extract_images_in_pdf=True,
    extract_image_block_types=['Image', 'Table'],
    extract_image_block_to_payload=True
)

# 画像として保持されている非構造データを確認する
for elem in raw_pdf_elements:
    if elem.category in ['Image', 'Table']:
        image_base64 = elem.metadata.image_base64
        decoded_image = base64.b64decode(image_base64)
        image = Image.open(io.BytesIO(decoded_image))
        print(f"Page Number: {elem.metadata.page_number}")
        display(image)  # Colab環境で画像を表示

を実行すると画像が表示される

import os
from unstructured.partition.pdf import partition_pdf

# 現在の作業ディレクトリを取得
current_dir = os.getcwd()

# 'data'フォルダのパスを設定
DATA_PAR_PATH = os.path.join(current_dir, 'data')

# 処理対象のPDFファイルのパスを設定
DATASET_PATH = os.path.join(DATA_PAR_PATH, '2024r06_ip_qs.pdf')

# 画像の出力先フォルダのパスを設定
OUTPUT_PATH = os.path.join(DATA_PAR_PATH, 'images')

# フォルダ確認(存在しない場合エラーになるのでアップロード確認用)
if not os.path.exists(DATA_PAR_PATH):
    raise FileNotFoundError(f"'data'フォルダが見つかりません。Google Colabに'2024r06_ip_qs.pdf'をアップロードしてください。")

if not os.path.exists(DATASET_PATH):
    raise FileNotFoundError(f"ファイル '2024r06_ip_qs.pdf' が'data'フォルダ内に存在しません。ファイルをアップロードしてください。")

# PDFファイル内のデータを分割する
raw_pdf_elements = partition_pdf(
    filename=DATASET_PATH,
    chunking_strategy='by_title',
    infer_table_structure=True,
    extract_images_in_pdf=True,
    extract_image_block_output_dir=OUTPUT_PATH
)

# 処理が成功したことを表示
print("PDFファイルの処理が完了しました。")
print(f"画像は以下のフォルダに保存されます: {OUTPUT_PATH}")

を実行すると dataフォルダの中に images が作成され
ここに抽出した画像が保存される

次はチラシで試す

Yomitokuで写真やレシートを解析をColabで試す

Yomitokuで写真やレシートを解析をColabで試す

Yomitokuで写真やレシートを解析してみる

Colab で行なってるのがあったので参考にする

出力形式によって得られる情報が異なるらしい

A100で実験する

https://github.com/kotaro-kinoshita/yomitoku
でライブラリが公開されているので
ドキュメントなどはこれを読む

基本的にGPUが必要

! pip install yomitoku

でライブラリインストール

最後にsession restartしろといわれたので、ダイアログボックスに促されるままrestartする

次に写真の用意

google colabなので、/content以下にimageフォルダを作成し、その中にJPGをいれ
フォルダをまるっと指定すると、その中の画像ファイルをすべて解析してくれます

!mkdir image

でフォルダ作成
ここに写真をアップロードする

aw10s/ollama/images/test.jpg

をアップロード

! yomitoku /content/image/ -f md -o results -v --figure

で解析

結果

2024-12-15 21:31:34,841 - yomitoku.base - INFO - Initialize TextDetector
model.safetensors: 100% 102M/102M [00:04<00:00, 23.8MB/s]
2024-12-15 21:31:40,639 - yomitoku.base - INFO - Initialize TextRecognizer
config.json: 100% 256/256 [00:00<00:00, 1.87MB/s]
model.safetensors: 100% 200M/200M [00:08<00:00, 23.9MB/s]
2024-12-15 21:31:50,844 - yomitoku.base - INFO - Initialize LayoutParser
model.safetensors: 100% 172M/172M [00:07<00:00, 23.5MB/s]
2024-12-15 21:31:59,554 - yomitoku.base - INFO - Initialize TableStructureRecognizer
model.safetensors: 100% 172M/172M [00:03<00:00, 43.0MB/s]
2024-12-15 21:32:04,793 - yomitoku.cli.main - INFO - Output directory: results
2024-12-15 21:32:04,793 - yomitoku.cli.main - INFO - Processing file: /content/image/test.jpg
2024-12-15 21:32:06,818 - yomitoku.base - INFO - TextDetector __call__ elapsed_time: 1.9037435054779053
2024-12-15 21:32:07,114 - yomitoku.base - INFO - LayoutParser __call__ elapsed_time: 2.19960355758667
2024-12-15 21:32:07,247 - yomitoku.base - INFO - TableStructureRecognizer __call__ elapsed_time: 0.13303065299987793
2024-12-15 21:32:08,789 - yomitoku.base - INFO - TextRecognizer __call__ elapsed_time: 1.9707973003387451
2024-12-15 21:32:08,863 - yomitoku.cli.main - INFO - Output file: results/image_test_p1_ocr.jpg
2024-12-15 21:32:08,914 - yomitoku.cli.main - INFO - Output file: results/image_test_p1_layout.jpg
2024-12-15 21:32:08,927 - yomitoku.cli.main - INFO - Output file: results/image_test_p1.md
2024-12-15 21:32:08,928 - yomitoku.cli.main - INFO - Total Processing time: 4.13 sec

結果は自動作成される results の中にある

ファイル名_p1.md
という感じで出力される
image_test_p1.md
の中身は

<img src="figures/image_test_p1_figure_0.png" width="200px"><br>
登録番号 T5080401017738<br>とれたて食楽部<br>静岡県袋井市山名町3\-3<br>TEL 0538\-41\-1100

2024年 8月10日\(土\)08:59 \#000011<br>000801精算機1<br>000801精算機1<br>3901

09:08<br>R9309<br>\#000003<br>お会計券<br>西澤<br>000008

¥150<br>内8 ★きゅうり/鈴木 仁<br>P2023300101503

内8 ★きゅうり/小林宗作

P2055600101303

¥130

内8 リーフレタス/\(有\)成神工 ¥216<br>P2086402402169

|小計<br>\(内税 8%対象額<br>買上点数|¥496|
|-|-|
||¥496\)|
||3点|
|合計|¥496|
|\(税率 8%対象額|¥496\)|
|\(内消費税等 8%|¥36\)|
|課税事業者||
|\(税率 8%対象額|¥216\)|
|\(内消費税等 8%|¥16\)|
|免税事業者||
|\(税率 8%対象額|¥280\)|

¥496<br>クレジット<br>¥36\)<br>\(内消費税等

、内Sは軽減税率対象商品です。

これがOCRした内容

次に
出力形式によって得られる情報が異なるらしいので
JSON形式で出力する

! yomitoku /content/image/ -f json -o results -v --figure

結果は

2024-12-16 21:00:01,501 - yomitoku.base - INFO - Initialize TextDetector
2024-12-16 21:00:02,677 - yomitoku.base - INFO - Initialize TextRecognizer
2024-12-16 21:00:04,059 - yomitoku.base - INFO - Initialize LayoutParser
2024-12-16 21:00:05,086 - yomitoku.base - INFO - Initialize TableStructureRecognizer
2024-12-16 21:00:06,063 - yomitoku.cli.main - INFO - Output directory: results
2024-12-16 21:00:06,063 - yomitoku.cli.main - INFO - Processing file: /content/image/test.jpg
2024-12-16 21:00:07,057 - yomitoku.base - INFO - TextDetector __call__ elapsed_time: 0.9070024490356445
2024-12-16 21:00:07,207 - yomitoku.base - INFO - LayoutParser __call__ elapsed_time: 1.0565669536590576
2024-12-16 21:00:07,340 - yomitoku.base - INFO - TableStructureRecognizer __call__ elapsed_time: 0.1329059600830078
2024-12-16 21:00:08,864 - yomitoku.base - INFO - TextRecognizer __call__ elapsed_time: 1.8073179721832275
2024-12-16 21:00:08,940 - yomitoku.cli.main - INFO - Output file: results/image_test_p1_ocr.jpg
2024-12-16 21:00:08,992 - yomitoku.cli.main - INFO - Output file: results/image_test_p1_layout.jpg
2024-12-16 21:00:08,994 - yomitoku.cli.main - INFO - Output file: results/image_test_p1.json
2024-12-16 21:00:08,995 - yomitoku.cli.main - INFO - Total Processing time: 2.93 sec

出力されたファイルは
Image_test_p1.json

内容は

{
    "figures": [
        {
            "box": [
                586,
                249,
                1633,
                503
            ],
            "direction": "horizontal",
            "order": 0,
            "paragraphs": []
        }
    ],
    "paragraphs": [
        {
            "box": [
                638,
                569,
                1548,
                872
            ],
            "contents": "登録番号 T5080401017738\nとれたて食楽部\n静岡県袋井市山名町3-3\nTEL 0538-41-1100",
            "direction": "horizontal",
            "order": 1,
            "role": null
        },
        {
            "box": [
                569,
                924,
                1614,
                1080
            ],
            "contents": "2024年 8月10日(土)08:59 #000011\n000801精算機1\n000801精算機1\n3901",
            "direction": "horizontal",
            "order": 2,
            "role": null
        },
        {
            "box": [
                545,
                1173,
                1636,
                1347
            ],
            "contents": "09:08\nR9309\n#000003\nお会計券\n西澤\n000008",
            "direction": "horizontal",
            "order": 3,
            "role": null
        },
        {
            "box": [
                516,
                1387,
                1688,
                1577
            ],
            "contents": "¥150\n内8 ★きゅうり/鈴木 仁\nP2023300101503",
            "direction": "horizontal",
            "order": 4,
            "role": null
        },
        {
            "box": [
                485,
                1558,
                1448,
                1660
            ],
            "contents": "内8 ★きゅうり/小林宗作",
            "direction": "horizontal",
            "order": 5,
            "role": null
        },
        {
            "box": [
                641,
                1652,
                1186,
                1734
            ],
            "contents": "P2055600101303",
            "direction": "horizontal",
            "order": 6,
            "role": null
        },
        {
            "box": [
                1532,
                1534,
                1703,
                1620
            ],
            "contents": "¥130",
            "direction": "horizontal",
            "order": 7,
            "role": null
        },
        {
            "box": [
                484,
                1695,
                1712,
                1904
            ],
            "contents": "内8 リーフレタス/(有)成神工 ¥216\nP2086402402169",
            "direction": "horizontal",
            "order": 8,
            "role": null
        },
        {
            "box": [
                341,
                3432,
                1884,
                3719
            ],
            "contents": "¥496\nクレジット\n¥36)\n(内消費税等",
            "direction": "horizontal",
            "order": 10,
            "role": null
        },
        {
            "box": [
                288,
                3822,
                1779,
                4077
            ],
            "contents": "、内Sは軽減税率対象商品です。",
            "direction": "horizontal",
            "order": 11,
            "role": null
        }
    ],
    "tables": [
        {
            "box": [
                346,
                1915,
                1852,
                3358
            ],
            "cells": [
                {
                    "box": [
                        347,
                        1921,
                        1279,
                        2310
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "小計\n(内税 8%対象額\n買上点数",
                    "row": 1,
                    "row_span": 3
                },
                {
                    "box": [
                        1276,
                        1925,
                        1851,
                        2039
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥496",
                    "row": 1,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2043,
                        1851,
                        2133
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥496)",
                    "row": 2,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2152,
                        1851,
                        2289
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "3点",
                    "row": 3,
                    "row_span": 1
                },
                {
                    "box": [
                        347,
                        2296,
                        1280,
                        2426
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "合計",
                    "row": 4,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2296,
                        1851,
                        2426
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥496",
                    "row": 4,
                    "row_span": 1
                },
                {
                    "box": [
                        348,
                        2424,
                        1280,
                        2526
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "(税率 8%対象額",
                    "row": 5,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2424,
                        1851,
                        2526
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥496)",
                    "row": 5,
                    "row_span": 1
                },
                {
                    "box": [
                        347,
                        2540,
                        1280,
                        2695
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "(内消費税等 8%",
                    "row": 6,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2540,
                        1851,
                        2695
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥36)",
                    "row": 6,
                    "row_span": 1
                },
                {
                    "box": [
                        348,
                        2705,
                        1280,
                        2852
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "課税事業者",
                    "row": 7,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2705,
                        1851,
                        2852
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "",
                    "row": 7,
                    "row_span": 1
                },
                {
                    "box": [
                        348,
                        2865,
                        1280,
                        2951
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "(税率 8%対象額",
                    "row": 8,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2865,
                        1851,
                        2951
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥216)",
                    "row": 8,
                    "row_span": 1
                },
                {
                    "box": [
                        347,
                        2980,
                        1280,
                        3102
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "(内消費税等 8%",
                    "row": 9,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        2980,
                        1851,
                        3102
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥16)",
                    "row": 9,
                    "row_span": 1
                },
                {
                    "box": [
                        348,
                        3103,
                        1280,
                        3202
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "免税事業者",
                    "row": 10,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        3103,
                        1851,
                        3202
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "",
                    "row": 10,
                    "row_span": 1
                },
                {
                    "box": [
                        347,
                        3211,
                        1280,
                        3355
                    ],
                    "col": 1,
                    "col_span": 1,
                    "contents": "(税率 8%対象額",
                    "row": 11,
                    "row_span": 1
                },
                {
                    "box": [
                        1276,
                        3211,
                        1851,
                        3355
                    ],
                    "col": 2,
                    "col_span": 1,
                    "contents": "¥280)",
                    "row": 11,
                    "row_span": 1
                }
            ],
            "n_col": 2,
            "n_row": 11,
            "order": 9
        }
    ],
    "words": [
        {
            "content": "、内Sは軽減税率対象商品です。",
            "det_score": 0.6796720981104631,
            "direction": "horizontal",
            "points": [
                [
                    431,
                    3885
                ],
                [
                    1752,
                    3813
                ],
                [
                    1759,
                    3925
                ],
                [
                    438,
                    3997
                ]
            ],
            "rec_score": 0.03351603075861931
        },
        {
            "content": "(内消費税等",
            "det_score": 0.8627398538033404,
            "direction": "horizontal",
            "points": [
                [
                    871,
                    3594
                ],
                [
                    1378,
                    3577
                ],
                [
                    1381,
                    3686
                ],
                [
                    875,
                    3704
                ]
            ],
            "rec_score": 0.979337215423584
        },
        {
            "content": "¥36)",
            "det_score": 0.7510144629009029,
            "direction": "horizontal",
            "points": [
                [
                    1694,
                    3557
                ],
                [
                    1881,
                    3557
                ],
                [
                    1881,
                    3664
                ],
                [
                    1694,
                    3664
                ]
            ],
            "rec_score": 0.9134319424629211
        },
        {
            "content": "クレジット",
            "det_score": 0.8124990954358461,
            "direction": "horizontal",
            "points": [
                [
                    350,
                    3484
                ],
                [
                    1270,
                    3465
                ],
                [
                    1272,
                    3569
                ],
                [
                    352,
                    3589
                ]
            ],
            "rec_score": 0.9985630512237549
        },
        {
            "content": "¥496",
            "det_score": 0.8485499834607593,
            "direction": "horizontal",
            "points": [
                [
                    1463,
                    3438
                ],
                [
                    1843,
                    3429
                ],
                [
                    1846,
                    3534
                ],
                [
                    1465,
                    3543
                ]
            ],
            "rec_score": 0.9998164176940918
        },
        {
            "content": "(税率 8%対象額",
            "det_score": 0.853462993147711,
            "direction": "horizontal",
            "points": [
                [
                    459,
                    3234
                ],
                [
                    1102,
                    3225
                ],
                [
                    1103,
                    3327
                ],
                [
                    460,
                    3336
                ]
            ],
            "rec_score": 0.9029322266578674
        },
        {
            "content": "¥280)",
            "det_score": 0.8697890050123379,
            "direction": "horizontal",
            "points": [
                [
                    1632,
                    3182
                ],
                [
                    1858,
                    3182
                ],
                [
                    1858,
                    3295
                ],
                [
                    1632,
                    3295
                ]
            ],
            "rec_score": 0.9970043301582336
        },
        {
            "content": "免税事業者",
            "det_score": 0.8758680560327103,
            "direction": "horizontal",
            "points": [
                [
                    357,
                    3103
                ],
                [
                    831,
                    3112
                ],
                [
                    829,
                    3219
                ],
                [
                    355,
                    3210
                ]
            ],
            "rec_score": 0.9983263611793518
        },
        {
            "content": "(内消費税等 8%",
            "det_score": 0.8655238629057851,
            "direction": "horizontal",
            "points": [
                [
                    475,
                    2996
                ],
                [
                    1100,
                    2996
                ],
                [
                    1100,
                    3093
                ],
                [
                    475,
                    3093
                ]
            ],
            "rec_score": 0.908987820148468
        },
        {
            "content": "¥16)",
            "det_score": 0.8736068132308011,
            "direction": "horizontal",
            "points": [
                [
                    1663,
                    2953
                ],
                [
                    1837,
                    2953
                ],
                [
                    1837,
                    3060
                ],
                [
                    1663,
                    3060
                ]
            ],
            "rec_score": 0.9977002143859863
        },
        {
            "content": "(税率 8%対象額",
            "det_score": 0.8736011394336691,
            "direction": "horizontal",
            "points": [
                [
                    488,
                    2884
                ],
                [
                    1100,
                    2884
                ],
                [
                    1100,
                    2981
                ],
                [
                    488,
                    2981
                ]
            ],
            "rec_score": 0.9527927041053772
        },
        {
            "content": "¥216)",
            "det_score": 0.8798753646381205,
            "direction": "horizontal",
            "points": [
                [
                    1613,
                    2841
                ],
                [
                    1827,
                    2835
                ],
                [
                    1830,
                    2940
                ],
                [
                    1616,
                    2946
                ]
            ],
            "rec_score": 0.9991167187690735
        },
        {
            "content": "課税事業者",
            "det_score": 0.8782089667459907,
            "direction": "horizontal",
            "points": [
                [
                    383,
                    2761
                ],
                [
                    839,
                    2773
                ],
                [
                    836,
                    2875
                ],
                [
                    381,
                    2863
                ]
            ],
            "rec_score": 0.9996485114097595
        },
        {
            "content": "(内消費税等 8%",
            "det_score": 0.8545332324999831,
            "direction": "horizontal",
            "points": [
                [
                    422,
                    2552
                ],
                [
                    1015,
                    2569
                ],
                [
                    1012,
                    2666
                ],
                [
                    419,
                    2649
                ]
            ],
            "rec_score": 0.9030265808105469
        },
        {
            "content": "¥36)",
            "det_score": 0.874239359391371,
            "direction": "horizontal",
            "points": [
                [
                    1637,
                    2517
                ],
                [
                    1801,
                    2517
                ],
                [
                    1801,
                    2614
                ],
                [
                    1637,
                    2614
                ]
            ],
            "rec_score": 0.9990556836128235
        },
        {
            "content": "(税率 8%対象額",
            "det_score": 0.8743577414363437,
            "direction": "horizontal",
            "points": [
                [
                    430,
                    2455
                ],
                [
                    1018,
                    2472
                ],
                [
                    1015,
                    2556
                ],
                [
                    427,
                    2539
                ]
            ],
            "rec_score": 0.9258973002433777
        },
        {
            "content": "¥496)",
            "det_score": 0.873335879837346,
            "direction": "horizontal",
            "points": [
                [
                    1584,
                    2421
                ],
                [
                    1787,
                    2411
                ],
                [
                    1792,
                    2503
                ],
                [
                    1589,
                    2513
                ]
            ],
            "rec_score": 0.9990760087966919
        },
        {
            "content": "合計",
            "det_score": 0.7989976852002054,
            "direction": "horizontal",
            "points": [
                [
                    422,
                    2351
                ],
                [
                    774,
                    2357
                ],
                [
                    772,
                    2459
                ],
                [
                    420,
                    2453
                ]
            ],
            "rec_score": 0.9596889615058899
        },
        {
            "content": "¥496",
            "det_score": 0.84043764577154,
            "direction": "horizontal",
            "points": [
                [
                    1423,
                    2337
                ],
                [
                    1756,
                    2319
                ],
                [
                    1761,
                    2406
                ],
                [
                    1428,
                    2424
                ]
            ],
            "rec_score": 0.9845718741416931
        },
        {
            "content": "買上点数",
            "det_score": 0.8724811626703719,
            "direction": "horizontal",
            "points": [
                [
                    474,
                    2164
                ],
                [
                    821,
                    2176
                ],
                [
                    818,
                    2263
                ],
                [
                    471,
                    2251
                ]
            ],
            "rec_score": 0.8529166579246521
        },
        {
            "content": "3点",
            "det_score": 0.877569906485891,
            "direction": "horizontal",
            "points": [
                [
                    1611,
                    2127
                ],
                [
                    1751,
                    2127
                ],
                [
                    1751,
                    2221
                ],
                [
                    1611,
                    2221
                ]
            ],
            "rec_score": 0.999936580657959
        },
        {
            "content": "(内税 8%対象額",
            "det_score": 0.8549906700132722,
            "direction": "horizontal",
            "points": [
                [
                    466,
                    2070
                ],
                [
                    1026,
                    2084
                ],
                [
                    1023,
                    2171
                ],
                [
                    464,
                    2157
                ]
            ],
            "rec_score": 0.6945281624794006
        },
        {
            "content": "¥496)",
            "det_score": 0.8776254550615946,
            "direction": "horizontal",
            "points": [
                [
                    1566,
                    2039
                ],
                [
                    1756,
                    2028
                ],
                [
                    1761,
                    2121
                ],
                [
                    1571,
                    2131
                ]
            ],
            "rec_score": 0.9979957938194275
        },
        {
            "content": "小計",
            "det_score": 0.8659234180608216,
            "direction": "horizontal",
            "points": [
                [
                    483,
                    1981
                ],
                [
                    677,
                    1981
                ],
                [
                    677,
                    2076
                ],
                [
                    483,
                    2076
                ]
            ],
            "rec_score": 0.66346675157547
        },
        {
            "content": "¥496",
            "det_score": 0.8556146869165837,
            "direction": "horizontal",
            "points": [
                [
                    1558,
                    1955
                ],
                [
                    1732,
                    1943
                ],
                [
                    1738,
                    2028
                ],
                [
                    1563,
                    2039
                ]
            ],
            "rec_score": 0.9997748136520386
        },
        {
            "content": "P2086402402169",
            "det_score": 0.8685337040086014,
            "direction": "horizontal",
            "points": [
                [
                    628,
                    1823
                ],
                [
                    1186,
                    1823
                ],
                [
                    1186,
                    1897
                ],
                [
                    628,
                    1897
                ]
            ],
            "rec_score": 0.994750440120697
        },
        {
            "content": "内8 リーフレタス/(有)成神工 ¥216",
            "det_score": 0.7733530013156038,
            "direction": "horizontal",
            "points": [
                [
                    471,
                    1719
                ],
                [
                    1716,
                    1690
                ],
                [
                    1718,
                    1800
                ],
                [
                    474,
                    1829
                ]
            ],
            "rec_score": 0.487512469291687
        },
        {
            "content": "P2055600101303",
            "det_score": 0.8620755339288183,
            "direction": "horizontal",
            "points": [
                [
                    641,
                    1658
                ],
                [
                    1185,
                    1652
                ],
                [
                    1186,
                    1729
                ],
                [
                    641,
                    1734
                ]
            ],
            "rec_score": 0.9976783394813538
        },
        {
            "content": "内8 ★きゅうり/小林宗作",
            "det_score": 0.8030553586848483,
            "direction": "horizontal",
            "points": [
                [
                    485,
                    1558
                ],
                [
                    1448,
                    1558
                ],
                [
                    1448,
                    1660
                ],
                [
                    485,
                    1660
                ]
            ],
            "rec_score": 0.8243062496185303
        },
        {
            "content": "¥130",
            "det_score": 0.8647632946312013,
            "direction": "horizontal",
            "points": [
                [
                    1532,
                    1541
                ],
                [
                    1700,
                    1534
                ],
                [
                    1703,
                    1613
                ],
                [
                    1536,
                    1620
                ]
            ],
            "rec_score": 0.9999488592147827
        },
        {
            "content": "P2023300101503",
            "det_score": 0.8535739641137016,
            "direction": "horizontal",
            "points": [
                [
                    654,
                    1502
                ],
                [
                    1183,
                    1497
                ],
                [
                    1183,
                    1566
                ],
                [
                    654,
                    1571
                ]
            ],
            "rec_score": 0.9996684789657593
        },
        {
            "content": "内8 ★きゅうり/鈴木 仁",
            "det_score": 0.7407760786246895,
            "direction": "horizontal",
            "points": [
                [
                    503,
                    1413
                ],
                [
                    1447,
                    1402
                ],
                [
                    1448,
                    1494
                ],
                [
                    504,
                    1505
                ]
            ],
            "rec_score": 0.9217264652252197
        },
        {
            "content": "¥150",
            "det_score": 0.8529803361907365,
            "direction": "horizontal",
            "points": [
                [
                    1521,
                    1386
                ],
                [
                    1685,
                    1376
                ],
                [
                    1691,
                    1455
                ],
                [
                    1527,
                    1465
                ]
            ],
            "rec_score": 0.9999033212661743
        },
        {
            "content": "000008",
            "det_score": 0.8420085177533121,
            "direction": "horizontal",
            "points": [
                [
                    918,
                    1276
                ],
                [
                    1151,
                    1269
                ],
                [
                    1153,
                    1341
                ],
                [
                    920,
                    1347
                ]
            ],
            "rec_score": 0.9971499443054199
        },
        {
            "content": "西澤",
            "det_score": 0.8301356971000148,
            "direction": "horizontal",
            "points": [
                [
                    1198,
                    1261
                ],
                [
                    1360,
                    1254
                ],
                [
                    1363,
                    1333
                ],
                [
                    1201,
                    1340
                ]
            ],
            "rec_score": 0.9971343278884888
        },
        {
            "content": "お会計券",
            "det_score": 0.8479825696054877,
            "direction": "horizontal",
            "points": [
                [
                    540,
                    1209
                ],
                [
                    835,
                    1209
                ],
                [
                    835,
                    1285
                ],
                [
                    540,
                    1285
                ]
            ],
            "rec_score": 0.9989036917686462
        },
        {
            "content": "#000003",
            "det_score": 0.832013468600706,
            "direction": "horizontal",
            "points": [
                [
                    884,
                    1207
                ],
                [
                    1148,
                    1198
                ],
                [
                    1150,
                    1269
                ],
                [
                    886,
                    1278
                ]
            ],
            "rec_score": 0.9912707805633545
        },
        {
            "content": "R9309",
            "det_score": 0.8094638501787745,
            "direction": "horizontal",
            "points": [
                [
                    1195,
                    1189
                ],
                [
                    1392,
                    1182
                ],
                [
                    1394,
                    1254
                ],
                [
                    1198,
                    1261
                ]
            ],
            "rec_score": 0.9985978603363037
        },
        {
            "content": "09:08",
            "det_score": 0.8513526355901968,
            "direction": "horizontal",
            "points": [
                [
                    1442,
                    1174
                ],
                [
                    1635,
                    1167
                ],
                [
                    1638,
                    1241
                ],
                [
                    1444,
                    1248
                ]
            ],
            "rec_score": 0.9983935952186584
        },
        {
            "content": "3901",
            "det_score": 0.8389774914979935,
            "direction": "horizontal",
            "points": [
                [
                    1465,
                    1031
                ],
                [
                    1622,
                    1024
                ],
                [
                    1625,
                    1100
                ],
                [
                    1468,
                    1108
                ]
            ],
            "rec_score": 0.9998389482498169
        },
        {
            "content": "000801精算機1",
            "det_score": 0.8261694877181531,
            "direction": "horizontal",
            "points": [
                [
                    557,
                    1015
                ],
                [
                    1029,
                    1004
                ],
                [
                    1031,
                    1068
                ],
                [
                    559,
                    1079
                ]
            ],
            "rec_score": 0.8924864530563354
        },
        {
            "content": "000801精算機1",
            "det_score": 0.7923262641892176,
            "direction": "horizontal",
            "points": [
                [
                    1130,
                    993
                ],
                [
                    1596,
                    965
                ],
                [
                    1599,
                    1024
                ],
                [
                    1134,
                    1052
                ]
            ],
            "rec_score": 0.8452281355857849
        },
        {
            "content": "2024年 8月10日(土)08:59 #000011",
            "det_score": 0.76677570112371,
            "direction": "horizontal",
            "points": [
                [
                    567,
                    950
                ],
                [
                    1601,
                    899
                ],
                [
                    1605,
                    971
                ],
                [
                    571,
                    1021
                ]
            ],
            "rec_score": 0.7705328464508057
        },
        {
            "content": "TEL 0538-41-1100",
            "det_score": 0.7891764333521688,
            "direction": "horizontal",
            "points": [
                [
                    899,
                    822
                ],
                [
                    1425,
                    800
                ],
                [
                    1428,
                    856
                ],
                [
                    902,
                    878
                ]
            ],
            "rec_score": 0.8409962058067322
        },
        {
            "content": "静岡県袋井市山名町3-3",
            "det_score": 0.8232278183336981,
            "direction": "horizontal",
            "points": [
                [
                    773,
                    750
                ],
                [
                    1545,
                    729
                ],
                [
                    1547,
                    795
                ],
                [
                    774,
                    817
                ]
            ],
            "rec_score": 0.9089908003807068
        },
        {
            "content": "とれたて食楽部",
            "det_score": 0.8368622312565417,
            "direction": "horizontal",
            "points": [
                [
                    905,
                    666
                ],
                [
                    1359,
                    657
                ],
                [
                    1360,
                    732
                ],
                [
                    906,
                    740
                ]
            ],
            "rec_score": 0.7296138405799866
        },
        {
            "content": "登録番号 T5080401017738",
            "det_score": 0.8375435412981505,
            "direction": "horizontal",
            "points": [
                [
                    640,
                    582
                ],
                [
                    1384,
                    566
                ],
                [
                    1386,
                    637
                ],
                [
                    642,
                    653
                ]
            ],
            "rec_score": 0.6307746171951294
        }
    ]
}

となっている

この2つのファイルを使って
日付,店名,商品名,数量,金額
を抽出し
CSVファイルにできるか試すことにする

chatGPTでは目的通りのCSVファイルが作成された

次は他のレシートでも実験してみる

~/Downloads/Photos-001/    

に色々Google Photo の写真があるので試す

ぴあごも問題なく抽出できる
ココカラファインもできる

ただし単品の金額ではなく
合計金額になっているので
プロンプトを変えることにする

データから日付,店名,商品名,数量,金額 を抽出し 金額の部分は単品の金額にして CSVファイルにして
としたが
これだとものによっては金額が単品になっていない

これは杏林堂などのレシートでも同じ

データから日付,店名,商品名,数量,単品価格 を抽出し CSVファイルにして
とプロンプトを変えても変わらなかった

Yomitokuで写真やレシートを解析

Yomitokuで写真やレシートを解析

Yomitokuで写真やレシートを解析してみる
では
Google Colab で実行しているが
レシート解析に成功している

なお
【Python】PyTorchをAppleシリコン搭載Mac(M1、M2)にインストールする方法 – AppleシリコンGPUで動かす方法も、併せて紹介 –

によれば

PyTorchをNvidia製GPUで動かすためには、扱うデータを「メインメモリ」から、
「GPU上のメモリ」に移す必要があります。

AppleシリコンGPUの場合も同じで、データを、メインメモリから、GPU上のメモリに移す処理が必要

import torch
print(torch.backends.mps.is_available())


True
となればOK

AppleシリコンGPUを使用する場合、
* device = torch.device(‘mps’)
* {データ}.to(device)
を使う

mpsとは、Metal Perfomance Shadersの略称

メモリのサイズが気になったのでChatGPTで調べてみた

1 MacBook Air(16GBモデル)のGPUメモリサイズは固定ではなく、
ユニファイドメモリ(16GB)の中から動的に割り当てられます。
最大で約8GB〜12GB程度が割り当て可能ですが、これはシステム負荷に依存します。

必要に応じてアクティビティモニタやPyTorchでリアルタイムの使用量を確認するのがおすすめです。

とりあえず実験を進める
https://www.muji.com/public/media/jp/doc/9952536/muji2021aw_all.pdf
無印良品 2021 秋冬 収納・家具・家電・ファブリック
からPDFダウンロード

トミカ&プラレールカタログwithあにあ 2022-2023
https://www.takaratomy.co.jp/products/plarail/catalog/2022_2023TPcatalog.pdf

これを
Data/imageフォルダに移動しておく

pip install yomitoku 

でyomitokuをインストール

次に

import cv2
import torch

from yomitoku import DocumentAnalyzer
from yomitoku.data.functions import load_image, load_pdf

if __name__ == "__main__":
    filename = "drugstore_flyer"
    pdf_filepath = f"./data/image/{filename}.pdf"

    image = load_pdf(pdf_filepath)
    analyzer = DocumentAnalyzer(
        configs={},
        visualize=True,
        device='mps'
    )

    results, ocr_vis, layout_vis = analyzer(image[0])

    # to HTML
    # results.to_html(f"./outputs/{filename}.html")

    # to image
    cv2.imwrite(f"./outputs/{filename}_ocr.jpg", ocr_vis)
    cv2.imwrite(f"./outputs/{filename}_layout.jpg", layout_vis)

として
pdf_ocr.py
を保存

次に実行
しかしこれだとエラーになるので

import cv2

from yomitoku import DocumentAnalyzer
from yomitoku.data.functions import load_image, load_pdf

pdf_filepath = f"document.pdf"

image = load_pdf(pdf_filepath)
analyzer = DocumentAnalyzer(
    configs={},
    visualize=True,
    device='mps'
)

results, ocr_vis, layout_vis = analyzer(image[0])


# to image
cv2.imwrite(f"document_ocr.jpg", ocr_vis)
cv2.imwrite(f"document_layout.jpg", layout_vis)

でファイルを1つにして実行する

しかし

2024-12-14 06:37:40,596 - yomitoku.base - INFO - Initialize TextDetector
model.safetensors: 100%|█████████████████████| 102M/102M [00:03<00:00, 34.0MB/s]
2024-12-14 06:37:45,343 - yomitoku.base - INFO - Initialize TextRecognizer
config.json: 100%|█████████████████████████████| 256/256 [00:00<00:00, 1.43MB/s]
model.safetensors: 100%|█████████████████████| 200M/200M [00:06<00:00, 30.7MB/s]
2024-12-14 06:37:53,752 - yomitoku.base - INFO - Initialize LayoutParser
model.safetensors: 100%|█████████████████████| 172M/172M [00:04<00:00, 34.5MB/s]
2024-12-14 06:37:59,630 - yomitoku.base - INFO - Initialize TableStructureRecognizer
model.safetensors: 100%|█████████████████████| 172M/172M [00:06<00:00, 28.3MB/s]
2024-12-14 06:38:07,932 - yomitoku.base - INFO - LayoutParser __call__ elapsed_time: 1.2879679203033447
2024-12-14 06:38:07,966 - yomitoku.base - INFO - TableStructureRecognizer __call__ elapsed_time: 0.03367877006530762
2024-12-14 06:38:09,561 - yomitoku.base - INFO - TextDetector __call__ elapsed_time: 2.916445255279541
2024-12-14 06:38:19,991 - yomitoku.base - INFO - Initialize TextDetector
2024-12-14 06:38:20,963 - yomitoku.base - INFO - Initialize TextRecognizer
2024-12-14 06:38:22,444 - yomitoku.base - INFO - Initialize LayoutParser
2024-12-14 06:38:23,230 - yomitoku.base - INFO - Initialize TableStructureRecognizer
2024-12-14 06:38:24,966 - yomitoku.base - INFO - LayoutParser __call__ elapsed_time: 1.029360055923462
2024-12-14 06:38:24,982 - yomitoku.base - INFO - TableStructureRecognizer __call__ elapsed_time: 0.01499795913696289
2024-12-14 06:38:26,832 - yomitoku.base - INFO - TextDetector __call__ elapsed_time: 2.895256757736206
2024-12-14 06:38:26,837 - yomitoku.base - ERROR - Error occurred in TextRecognizer __call__: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/spawn.py", line 125, in _main
    prepare(preparation_data)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/runpy.py", line 289, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/Users/snowpool/aw10s/ollama/pdf_ocr.py", line 15, in <module>
    results, ocr_vis, layout_vis = analyzer(image[0])
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/yomitoku/document_analyzer.py", line 304, in __call__
    resutls, ocr, layout = asyncio.run(self.run(img))
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/yomitoku/document_analyzer.py", line 293, in run
    results = await asyncio.gather(*tasks)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/yomitoku/ocr.py", line 83, in __call__
    rec_outputs, vis = self.recognizer(img, det_outputs.points, vis=vis)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/yomitoku/base.py", line 45, in wrapper
    raise e
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/yomitoku/base.py", line 40, in wrapper
    result = func(*args, **kwargs)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/yomitoku/text_recognizer.py", line 103, in __call__
    for data in dataloader:
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 484, in __iter__
    return self._get_iterator()
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 415, in _get_iterator
    return _MultiProcessingDataLoaderIter(self)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 1138, in __init__
    w.start()
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/process.py", line 121, in start
    self._popen = self._Popen(self)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/context.py", line 288, in _Popen
    return Popen(process_obj)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/popen_spawn_posix.py", line 32, in __init__
    super().__init__(process_obj)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/popen_fork.py", line 19, in __init__
    self._launch(process_obj)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/popen_spawn_posix.py", line 42, in _launch
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/multiprocessing/spawn.py", line 134, in _check_not_importing_main
    raise RuntimeError('''
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

となる

このエラーメッセージは、

multiprocessing モジュールを使用する際に適切なプロセス起動方法が設定されていないことが原因です。
特に、macOSではデフォルトで spawn を使用してプロセスを開始するため、
if __name__ == “__main__”: を使用しないとこのエラーが発生します。
以下の修正版コードを使用して、この問題を解決できます。

とのこと

import cv2
import torch

from yomitoku import DocumentAnalyzer
from yomitoku.data.functions import load_image, load_pdf

if __name__ == "__main__":
    filename = "drugstore_flyer"
    pdf_filepath = f"./images/{filename}.pdf"

    image = load_pdf(pdf_filepath)
    analyzer = DocumentAnalyzer(
        configs={},
        visualize=True,
        device='mps'
    )

    results, ocr_vis, layout_vis = analyzer(image[0])

    # to HTML
    # results.to_html(f"./outputs/{filename}.html")

    # to image
    cv2.imwrite(f"./outputs/{filename}_ocr.jpg", ocr_vis)
    cv2.imwrite(f"./outputs/{filename}_layout.jpg", layout_vis)


https://github.com/Shakshi3104/ymtk-supplementary/blob/main/app.py
にあったのでコードを書き換える

import cv2
import torch

from yomitoku import DocumentAnalyzer
from yomitoku.data.functions import load_image, load_pdf

if __name__ == "__main__":
    filename = "document"
    pdf_filepath = f"./images/{filename}.pdf"

    image = load_pdf(pdf_filepath)
    analyzer = DocumentAnalyzer(
        configs={},
        visualize=True,
        device='mps'
    )

    results, ocr_vis, layout_vis = analyzer(image[0])

    # to HTML
    # results.to_html(f"./outputs/{filename}.html")

    # to image
    cv2.imwrite(f"./outputs/{filename}_ocr.jpg", ocr_vis)
    cv2.imwrite(f"./outputs/{filename}_layout.jpg", layout_vis)

として

mkdir outputs  
mv document.pdf images/

でPDFを移動して
出力先のフォルダも作成しておく

これで実行すると

2024-12-15 05:50:41,470 - yomitoku.base - INFO - Initialize TextDetector
2024-12-15 05:50:42,794 - yomitoku.base - INFO - Initialize TextRecognizer
2024-12-15 05:50:44,762 - yomitoku.base - INFO - Initialize LayoutParser
2024-12-15 05:50:45,957 - yomitoku.base - INFO - Initialize TableStructureRecognizer
2024-12-15 05:50:48,155 - yomitoku.base - INFO - LayoutParser __call__ elapsed_time: 1.2731208801269531
2024-12-15 05:50:48,189 - yomitoku.base - INFO - TableStructureRecognizer __call__ elapsed_time: 0.033370256423950195
2024-12-15 05:50:49,887 - yomitoku.base - INFO - TextDetector __call__ elapsed_time: 3.005059003829956
2024-12-15 05:51:04,448 - yomitoku.base - INFO - TextRecognizer __call__ elapsed_time: 14.56023383140564
snowpool@kubotasorunoAir ollama % mkdir outputs
snowpool@kubotasorunoAir ollama % python pdf_ocr.py
2024-12-15 05:52:39,988 - yomitoku.base - INFO - Initialize TextDetector
2024-12-15 05:52:41,732 - yomitoku.base - INFO - Initialize TextRecognizer
2024-12-15 05:52:43,589 - yomitoku.base - INFO - Initialize LayoutParser
2024-12-15 05:52:44,413 - yomitoku.base - INFO - Initialize TableStructureRecognizer
2024-12-15 05:52:46,277 - yomitoku.base - INFO - LayoutParser __call__ elapsed_time: 1.1299068927764893
2024-12-15 05:52:46,312 - yomitoku.base - INFO - TableStructureRecognizer __call__ elapsed_time: 0.03462696075439453
2024-12-15 05:52:48,106 - yomitoku.base - INFO - TextDetector __call__ elapsed_time: 2.958970069885254
2024-12-15 05:53:01,007 - yomitoku.base - INFO - TextRecognizer __call__ elapsed_time: 12.900847911834717

となるが
最初のページのみしか処理されない

これは

load_pdf関数がPDFを画像に変換した際、最初のページだけを image[0] で指定しているため、
最初のページしか処理されていない状況です。
すべてのページを処理するには、PDF内のすべてのページをループするようにコードを修正します。

とのこと

これをコードを変えて全ページを実行してみるが

ページ数は147
処理開始が6時5分
とりあえず半分やるだけで1時間以上かかるので停止

次はレシートをcolabでやってみる

Firestore DBからメッセージ取得と読み上げ

Firestore DBからメッセージ取得と読み上げ

import warnings
from google.cloud import firestore
import datetime
import absl.logging
import requests
import os
import glob
from playsound import playsound

# 警告を無視する設定
warnings.filterwarnings("ignore", category=UserWarning, module="google.cloud.firestore_v1.base_collection")
# Firestore クライアントの初期化
db = firestore.Client.from_service_account_json("serviceAccountKey.json")

# VoiceVoxの設定
VOICEVOX_API_URL = "http://192.168.1.69:50021"

def synthesize_speech(text, speaker=1):
    """指定されたテキストを音声に合成してファイル名を返す関数"""
    params = {'text': text, 'speaker': speaker}
    response = requests.post(f"{VOICEVOX_API_URL}/audio_query", params=params)
    if response.status_code == 200:
        query_data = response.json()
        synthesis_response = requests.post(f"{VOICEVOX_API_URL}/synthesis", params={'speaker': speaker}, json=query_data)
        if synthesis_response.status_code == 200:
            filename = f"event_voice_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.wav"
            with open(filename, "wb") as f:
                f.write(synthesis_response.content)
            return filename
    return None

def play_audio_file(filename):
    """音声ファイルを再生する関数"""
    if os.path.exists(filename):
        playsound(filename)

def read_unread_messages():
    messages_ref = db.collection("messages").where("user_id", "==", target_user_id).where("read", "==", False)
    unread_messages = messages_ref.stream()

    for message in unread_messages:
        message_data = message.to_dict()
        message_text = message_data["text"]
        # 音声合成してファイルを生成
        audio_filename = synthesize_speech(message_text)
        if audio_filename:
            # 音声ファイルを再生
            play_audio_file(audio_filename)
            # メッセージを既読に更新
            message.reference.update({"read": True})
            # 生成された音声ファイルを後でクリーンアップ
            os.remove(audio_filename)

# 特定のユーザーIDを指定してメッセージを取得して読み上げる
target_user_id = ""
read_unread_messages()

Firestoreからメッセージを取得して、未読メッセージを音声で読み上げ、
その後に音声ファイルを整理する一連の処理を実行

Linebotの既読のフラグの追加

既読のフラグの追加

Firestoreで取得したメッセージを既読に設定するために、取得した後に各メッセージのread属性をTrueに更新する処理を追加

import warnings
from google.cloud import firestore
import datetime
import absl.logging

# 警告を無視する設定
warnings.filterwarnings("ignore", category=UserWarning, module="google.cloud.firestore_v1.base_collection")

# Firestore クライアントの初期化
db = firestore.Client.from_service_account_json("serviceAccountKey.json")

# gRPCの警告を抑制
absl.logging.set_verbosity("info")

def get_user_messages(user_id):
    messages_ref = db.collection("messages")
    now = datetime.datetime.now()
    
    # 24時間以内のメッセージを取得するクエリ
    query = messages_ref.where("user_id", "==", user_id).where("timestamp", ">=", now - datetime.timedelta(days=1))
    # 24時間以上前のメッセージを削除するクエリ
    old_messages_query = messages_ref.where("user_id", "==", user_id).where("timestamp", "<", now - datetime.timedelta(days=1))

    # メッセージを取得してリストに格納
    user_messages = []
    for doc in query.stream():
        user_messages.append(doc.to_dict())
        # メッセージを既読に設定
        doc.reference.update({"read": True})
    
    # 古いメッセージを削除
    for doc in old_messages_query.stream():
        doc.reference.delete()

    return user_messages

# 特定のユーザーIDを指定してメッセージを取得
user_id = ""
messages = get_user_messages(user_id)

for message in messages:
    print(f"メッセージ: {message['text']}, タイムスタンプ: {message['timestamp']}")

以下GPTの解説
メッセージの取得時にそのメッセージをread属性をTrueに設定する処理を追加したことです。

これにより、メッセージを取得すると同時にそれらを既読としてマークし、
次回のクエリではそれらが含まれないようにします。
これは、アプリケーションで未読メッセージを効率的に処理するために有効です。

Linebot の24時間経過したメッセージの削除

24時間経過したメッセージの削除

import warnings
from google.cloud import firestore
import datetime
import absl.logging

# 警告を無視する設定
warnings.filterwarnings("ignore", category=UserWarning, module="google.cloud.firestore_v1.base_collection")

# Firestore クライアントの初期化
db = firestore.Client.from_service_account_json("serviceAccountKey.json")

# gRPCの警告を抑制
absl.logging.set_verbosity("info")

def get_user_messages(user_id):
    messages_ref = db.collection("messages")
    
    # 複数条件のクエリを設定
    query = messages_ref.where("user_id", "==", user_id).where("timestamp", ">=", datetime.datetime.now() - datetime.timedelta(days=1))
    
    # メッセージを取得してリストに格納
    user_messages = []
    for doc in query.stream():
        user_messages.append(doc.to_dict())

    return user_messages

# 特定のユーザーIDを指定してメッセージを取得
user_id = ""
messages = get_user_messages(user_id)

for message in messages:
    print(f"メッセージ: {message['text']}, タイムスタンプ: {message['timestamp']}")

では24時間以内のメッセージのみ取得して表示している

ストレージの確保のため
24時間経過したメッセージは削除する

import warnings
from google.cloud import firestore
import datetime
import absl.logging

# 警告を無視する設定
warnings.filterwarnings("ignore", category=UserWarning, module="google.cloud.firestore_v1.base_collection")

# Firestore クライアントの初期化
db = firestore.Client.from_service_account_json("serviceAccountKey.json")

# gRPCの警告を抑制
absl.logging.set_verbosity("info")

def get_user_messages(user_id):
    messages_ref = db.collection("messages")
    now = datetime.datetime.now()
    
    # 24時間以内のメッセージを取得するクエリ
    query = messages_ref.where("user_id", "==", user_id).where("timestamp", ">=", now - datetime.timedelta(days=1))
    # 24時間以上前のメッセージを削除するクエリ
    old_messages_query = messages_ref.where("user_id", "==", user_id).where("timestamp", "<", now - datetime.timedelta(days=1))

    # メッセージを取得してリストに格納
    user_messages = []
    for doc in query.stream():
        user_messages.append(doc.to_dict())
    
    # 古いメッセージを削除
    for doc in old_messages_query.stream():
        doc.reference.delete()

    return user_messages

# 特定のユーザーIDを指定してメッセージを取得
user_id = ""
messages = get_user_messages(user_id)

for message in messages:
    print(f"メッセージ: {message['text']}, タイムスタンプ: {message['timestamp']}")

として実行

/Users/snowpool/aw10s/linebot/get_message.py:20: UserWarning: Detected filter using positional arguments. Prefer using the 'filter' keyword argument instead.
  query = messages_ref.where("user_id", "==", user_id).where("timestamp", ">=", now - datetime.timedelta(days=1))
/Users/snowpool/aw10s/linebot/get_message.py:22: UserWarning: Detected filter using positional arguments. Prefer using the 'filter' keyword argument instead.
  old_messages_query = messages_ref.where("user_id", "==", user_id).where("timestamp", "<", now - datetime.timedelta(days=1))
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1732049170.984219 4556639 config.cc:230] gRPC experiments enabled: call_status_override_on_cancellation, event_engine_dns, event_engine_listener, http2_stats_fix, monitoring_experiment, pick_first_new, trace_record_callops, work_serializer_clears_time_cache
メッセージ: 本日は厳しい冷え込みだ, タイムスタンプ: 2024-11-19 20:43:21+00:00

となって24時間経過したメッセージは消えた

次にこのコードに既読フラグをつけたいが
その前になぜ前回のコードが機能しなかったのかまとめておく

from google.cloud import firestore
from datetime import datetime, timedelta, timezone
import requests
import warnings

# JSONファイルで認証情報を指定
db = firestore.Client.from_service_account_json("serviceAccountKey.json")

# 特定のユーザーID
target_user_id = ""

# VoiceVox APIの設定
VOICEVOX_API_URL = "http://192.168.1.69:50021"
VOICEVOX_SPEAKER_ID = 1

def read_unread_messages():
    # UTCの現在時刻を取得
    current_time = datetime.now(timezone.utc)
    messages_ref = db.collection("messages").where("user_id", "==", target_user_id).where("read", "==", False)
    unread_messages = messages_ref.stream()

    for message in unread_messages:
        message_data = message.to_dict()
        message_text = message_data["text"]
        # FirestoreのタイムスタンプをUTCに変換
        message_time = message_data["timestamp"].replace(tzinfo=timezone.utc)

        print(f"Checking message: {message_text} at {message_time}, Time difference: {current_time - message_time}")
        if current_time - message_time > timedelta(hours=24):
            print(f"Deleting message: {message_text} at {message_time}")
            message.reference.delete()
        else:
            print(f"Not deleting message: {message_text} at {message_time}")

        read_message_aloud(message_text)
        message.reference.update({"read": True})

def read_message_aloud(text):
    query_response = requests.post(f"{VOICEVOX_API_URL}/audio_query", params={"text": text, "speaker": VOICEVOX_SPEAKER_ID})
    if query_response.status_code == 200:
        synthesis_response = requests.post(f"{VOICEVOX_API_URL}/synthesis", params={"speaker": VOICEVOX_SPEAKER_ID}, json=query_response.json())
        if synthesis_response.status_code == 200:
            print(f"Message read aloud: {text}")
        else:
            print("Failed to read aloud:", synthesis_response.text)
    else:
        print("Failed to generate audio query:", query_response.text)

read_unread_messages()

の場合

from datetime import datetime, timedelta, timezone

def read_unread_messages():
    current_time = datetime.now(timezone.utc)
    messages_ref = db.collection("messages").where("user_id", "==", target_user_id).where("read", "==", False)
    unread_messages = messages_ref.stream()

    for message in unread_messages:
        message_data = message.to_dict()
        message_time = message_data["timestamp"].replace(tzinfo=timezone.utc)

        if current_time - message_time > timedelta(hours=24):
            print(f"Deleting message: {message_text} at {message_time}")
            message.reference.delete()
        else:
            print(f"Not deleting message: {message_text} at {message_time}")

の場合
タイムスタンプをUTC時刻に変換してから、現在時刻との差を計算して24時間を超えていればメッセージを削除

ここでのタイムスタンプはtimestampフィールドから取得され、その値がすでにUTC時刻である必要がある

今回の場合は

import datetime

def get_user_messages(user_id):
    now = datetime.datetime.now()
    old_messages_query = messages_ref.where("user_id", "==", user_id).where("timestamp", "<", now - datetime.timedelta(days=1))

    for doc in old_messages_query.stream():
        doc.reference.delete()


現在時刻から1日前の時刻を計算し、それよりも前のタイムスタンプを持つメッセージをクエリで直接検索

この場合、Firestoreのtimestampは自動的にUTCで扱われるため、時差を考慮する必要がない

GPTによれば

違い
1. タイムゾーンの扱い:
* 最初のコードでは、メッセージのタイムスタンプをUTCに明示的に変換して比較しています。
* 二番目のコードでは、タイムスタンプがUTCであると仮定して、クエリで直接比較しています。
2. クエリの利用:
* 最初のコードでは、すべての未読メッセージをストリームで取得してから条件分岐を行い、必要に応じて削除しています。
* 二番目のコードでは、24時間以上古いメッセージに対して直接クエリを発行し、その結果に基づいて削除しています。

最初のコードが削除できなかった可能性として、タイムスタンプの変換や時差の取り扱いが適切でなかったか、Firestoreの設定やデータの整合性に問題がある可能性が考えられます。また、read属性がFalseに設定されたままのメッセージが削除の条件に含まれていなかったことも影響しているかもしれません

とあるが
最後の read属性についてはハズレで
これがFalseでも削除されている