end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

oracle linux on wsl2 を用いた win11内への claude code用sandbox

https://end0tknr.hateblo.jp/entry/20261026/1792962540

先日の上記entryの oracle linux版です

目次

wsl自体のインストールと最新化

windowsのコマンドプロンプトから以下を実行後、pc再起動

CMD> wsl --install
CMD> wsl --update

wslへの Oracle Linuxのインストールと最新化

windowsのコマンドプロンプトからOracle Linuxのインストール

※インストール中に聞かれるusernameは、要調整

# オンライン配布されているlinux distributionの一覧確認
CMD> wsl --list --online

# oracle linuxのインストール
CMD> wsl --install OracleLinux_9_5

# oracle linuxの起動。起動するとプロンプト表示が変更
CMD> wsl -d OracleLinux_9_5
[ユーザ名@ホスト名 ~]$

今回のPCはproxy内にある為、wsl内のdnf.conf編集と、windows内に.wslconfig新規作成

$ sudo vi /etc/dnf/dnf.conf

[main]
gpgcheck=1
installonly_limit=3
clean_requirements_on_remove=True
best=True
skip_if_unavailable=False
assumeyes=True
sslverify=False  # 行追加
CMD> vi c:/Users/ユーザ名/.wslconfig

[wsl2]
networkingMode=consomme
dnsTunneling=true
autoProxy=true

Oracle Linuxの最新化

$ sudo dnf update

sysytemdによるdaemonを利用できる様、wsl.conf を編集後、wsl再起動

$ sudo vi /etc/wsl.conf

[boot]
systemd=true

wsl 再起動

停止 CMD> wsl --shutdown
起動 CMD> wsl

pythonはoracle linux付属のものを利用

python本体はインストール済みでしたので、pipのみ追加

$ /usr/bin/python3 --version
Python 3.9.25
$ sudo dnf install python3-pip

Claude Codeインストール

https://code.claude.com/docs/ja/setup

Claude Codeインストール

$ sudo tee /etc/yum.repos.d/claude-code.repo <<'EOF'
[claude-code]
name=Claude Code
baseurl=https://downloads.claude.ai/claude-code/rpm/stable
enabled=1
gpgcheck=1
gpgkey=https://downloads.claude.ai/keys/claude-code.asc
EOF

$ sudo dnf install claude-code

環境変数PATHの編集や、インストールされたclaudeのバージョン確認

$ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
$ source ~/.bashrc

$ claude --version
2.1.311 (Claude Code)

windows側dirのmount

$ sudo mkdir -p /mnt/claude_pc
$ sudo mkdir -p /mnt/claude_share
$ cd
$ ln -s /mnt/claude_pc .
$ ln -s /mnt/claude_share .
$ sudo vi /etc/fstab

C:/claude_pc             /mnt/claude_pc    drvfs rw,nofail 0 0
S:/software/claude_share /mnt/claude_share drvfs ro,nofail 0 0

※ rw:読書きOK、ro:読取りのみ

接続先の制限

必要パッケージのインストール

$ sudo dnf install \
    squid \
    iptables \
    iptables-services \
    curl \
    jq \
    procps-ng \
    shadow-utils \
    tree

squidによる接続先制限

squid.confをバックアップ後、書換え

$ sudo cp -a /etc/squid/squid.conf /etc/squid/squid.conf.org

$ sudo vi /etc/squid/squid.conf

squid.confの書換え内容は以下

# WSL内部からのみ利用可能
http_port 127.0.0.1:3128

# Claude Code関連の接続先
acl allowed_domains dstdomain \
    .oracle.com \
    .anthropic.com \
    .claude.ai \
    .claude.com \
    .statsig.com \
    .sentry.io \
    .pypi.org \
    .pythonhosted.org
    #.github.com \
    #.githubusercontent.com

# HTTPS CONNECTは443番ポートのみ
acl SSL_ports port 443
acl CONNECT method CONNECT

# HTTPS:許可ドメインのみ
http_access deny CONNECT !SSL_ports
http_access allow CONNECT allowed_domains

# HTTP:許可ドメインなら任意のポートを許可
http_access allow allowed_domains

# その他はすべて拒否
http_access deny all

# キャッシュを使用しない
cache deny all

# win pcのあるproxyのssl verifyを解除
sslproxy_cert_error allow all
# tls_outgoing_options flags=DONT_VERIFY_PEER

設定検証後、squid起動

$ sudo squid -k parse

2026/11/14 06:31:51| Startup: Initializing Authentication Schemes ...
2026/11/14 06:31:51| Startup: Initialized Authentication Scheme 'basic'
2026/11/14 06:31:51| Startup: Initialized Authentication Scheme 'digest'
2026/11/14 06:31:51| Startup: Initialized Authentication Scheme 'negotiate'
2026/11/14 06:31:51| Startup: Initialized Authentication Scheme 'ntlm'
2026/11/14 06:31:51| Startup: Initialized Authentication.
2026/11/14 06:31:51| Processing Configuration File: /etc/squid/squid.conf (depth 0)
2026/11/14 06:31:51| Processing: http_port 127.0.0.1:3128
2026/11/14 06:31:51| Processing: acl allowed_domains dstdomain .anthropic.com .claude.ai .claude.com .statsig.com .sentry.io
2026/11/14 06:31:51| Processing: acl SSL_ports port 443
2026/11/14 06:31:51| Processing: acl CONNECT method CONNECT
2026/11/14 06:31:51| Processing: http_access deny CONNECT !SSL_ports
2026/11/14 06:31:51| Processing: http_access allow CONNECT allowed_domains
2026/11/14 06:31:51| Processing: http_access deny all
2026/11/14 06:31:51| Processing: cache deny all
2026/11/14 06:31:51| Processing: sslproxy_cert_error allow all
2026/11/14 06:31:51| Initializing https:// proxy context
2026/11/14 06:31:51| Requiring client certificates.
$ sudo systemctl enable --now squid
$ sudo systemctl status squid

squidの設定反映を行う場合、以下

$ sudo squid -k reconfigure

iptablesによるファイアウォール設定

現在のルールを確認

$ sudo iptables -S OUTPUT
-P OUTPUT ACCEPT

$ sudo ip6tables -S OUTPUT
-P OUTPUT ACCEPT
$ sudo vi /usr/local/sbin/firewall.sh

で、以下の firewall.sh を作成

#!/bin/bash
set -eu

# Squidの実行ユーザーを確認
SQUID_USER="$(systemctl show squid -p User --value)"

# systemdのUserが空の場合は、Oracle Linux標準のsquidを使用
if [ -z "$SQUID_USER" ]; then
    SQUID_USER="squid"
fi

# Squidユーザーが存在することを確認
id "$SQUID_USER" >/dev/null

# IPv4: 外向き通信をデフォルト拒否
iptables -F OUTPUT
iptables -P OUTPUT DROP

# ループバック通信
iptables -A OUTPUT -o lo -j ACCEPT

# 既存接続の応答を許可
iptables -A OUTPUT \
    -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# SquidだけDNS問い合わせを許可
iptables -A OUTPUT \
    -m owner --uid-owner "$SQUID_USER" \
    -p udp --dport 53 -j ACCEPT

iptables -A OUTPUT \
    -m owner --uid-owner "$SQUID_USER" \
    -p tcp --dport 53 -j ACCEPT

# Squid経由なら許可ドメインの任意TCPポートにアクセス可
iptables -A OUTPUT \
    -m owner --uid-owner "$SQUID_USER" \
    -p tcp -j ACCEPT

# IPv6: 外向き通信を遮断
ip6tables -F OUTPUT
ip6tables -P OUTPUT DROP
ip6tables -A OUTPUT -o lo -j ACCEPT
ip6tables -A OUTPUT \
    -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

exit 0
$ sudo chmod 750 /usr/local/sbin/firewall.sh

設定を恒久化する前に、まず手動で適用します。

$ sudo /usr/local/sbin/firewall.sh


$ sudo iptables -S OUTPUT
-P OUTPUT DROP
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -p udp -m owner --uid-owner 23 -m udp --dport 53 -j ACCEPT
-A OUTPUT -p tcp -m owner --uid-owner 23 -m tcp --dport 53 -j ACCEPT
-A OUTPUT -p tcp -m owner --uid-owner 23 -m tcp --dport 443 -j ACCEPT
$ sudo ip6tables -S OUTPUT
-P OUTPUT DROP
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

/etc/wsl.conf 設定

Windowsとの連携を制限し、WSL起動時にファイアウォールを適用

$ sudo vi /etc/wsl.conf
[boot]
systemd=true

# WSL起動時にファイアウォールを適用
command="/usr/local/sbin/firewall.sh"

# Cドライブの自動マウントは無効化するが、fstabによるマウントは許可
[automount]
enabled=false
mountFsTab=true

[interop]
# Windows実行ファイルとの連携を無効化
enabled=false

# Windows側のPATHを引き継がない
appendWindowsPath=false

[user]
# 通常起動時のユーザーを指定
default=ないしょ021
$ vi ~/.bashrc

により .bashrc の末尾に以下を追加

# Claude Code用プロキシ 大文字&小文字
export HTTP_PROXY=http://127.0.0.1:3128
export HTTPS_PROXY=http://127.0.0.1:3128
export http_proxy=http://127.0.0.1:3128
export https_proxy=http://127.0.0.1:3128

# 自動更新と不要な通信を抑制
# export DISABLE_AUTOUPDATER=1
# export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1

# SSL検証を無効化
export NODE_TLS_REJECT_UNAUTHORIZED=0

wsl再起動

CMD> wsl --shutdown
CMD> wsl

動作確認

windowsとの連携を禁止できていることを確認

cは何も表示されず、一方、 mountの claude_pc、claude_share表示ならOK

$ ls /mnt/c
$ ls /mnt/claude_pc
$ ls /mnt/claude_share

command not foundなら、OK

$ cmd.exe

接続拒否なら、OK

$ curl -v -m 10 --proxy http://127.0.0.1:3128 --ssl-no-revoke \
  https://www.google.com/

$ curl -v -m 10 --noproxy '*' --ssl-no-revoke \
    https://www.google.com/

Claude Code関連が接続できれば、OK

$ curl -v -m 15 --proxy http://127.0.0.1:3128  --ssl-no-revoke \
    https://api.anthropic.com/

$ curl -v -m 15 --noproxy '*' --ssl-no-revoke \
    https://api.anthropic.com/

Claude Codeを起動できれば、OK

$ claude
Welcome to Claude Code v2.1.311

 Unable to connect to Anthropic services

 Failed to connect to api.anthropic.com: ERR_PROXY_TUNNEL

 A proxy is configured via HTTPS_PROXY.
 Check that it allows connections to the host above. See
 https://code.claude.com/docs/en/network-config

 Please check your internet connection and network settings.

 Note: Claude Code might not be available in your country.
 Check supported countries at
 https://anthropic.com/supported-countries

テストに失敗し、squidのログを確認する場合は以下

$ sudo tail -f /var/log/squid/access.log
1794555969.171      0 127.0.0.1 TCP_DENIED/403 3435 CONNECT api.anthropic.com:443 - HIER_NONE/- text/html
1794555969.171      0 127.0.0.1 TCP_DENIED/403 3439 CONNECT platform.claude.com:443 - HIER_NONE/- text/html

ログの収集

$ sudo dnf install -y cronie
$ sudo systemctl enable --now crond

$ sudo crontab -e
5 * * * * /usr/bin/tar czf /home/claude/claude_pc/claude_log_$(/usr/bin/cat /etc/hostname)_$(/usr/bin/date +\%m\%d).tar.gz -C /home/claude .claude/projects .claude.json -C /var/log/squid access.log
@reboot sleep 60 && /usr/bin/tar czf /home/claude/claude_pc/claude_log_$(/usr/bin/cat /etc/hostname)_$(/usr/bin/date +\%m\%d).tar.gz -C /home/claude .claude/projects .claude.json -C /var/log/squid access.log

作業ユーザからsudo権限削除

$ sudo gpasswd -d ないしょ021 wheel

※ 管理者として起動する場合は、Windows側から次のようにwslを起動

CMD> wsl -d OracleLinux_9_5 -u root

proxy内にあるwsl on win11の yum installで SSLエラー

エラーの内容

$ sudo yum install httpd
  :
Oracle Linux 9 BaseOS Latest (x86_64)        0.0  B/s |  0  B   00:00
Errors during downloading metadata for repository 'ol9_baseos_latest':
  - Curl error (60): SSL peer certificate or SSH remote key was not OK
    for https://yum.oracle.com/repo/OracleLinux/OL9/baseos/latest/x86_64/repodata/repomd.xml
    [SSL certificate problem: self-signed certificate in certificate chain]
Error: Failed to download metadata for repo 'ol9_baseos_latest':
Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

非推奨だが、SSL検証を無効化

$ sudo vi /etc/dnf/dnf.conf

sslverify=0 ## ADD

キャッシュをクリア

$ sudo dnf clean all
$ sudo dnf repolist
repo id            repo name
ol9_appstream      Oracle Linux 9 Application Stream Packages (x86_64)
ol9_baseos_latest  Oracle Linux 9 BaseOS Latest (x86_64)

powershellから wifi速度をcloudflareで計測し、csvに保存

powershellから wifi速度をspeedtestで計測し、csvに保存 - end0tknr's kipple - web写経開発

先日作成した上記entryのps1をタスクスケジューラで定期実行したところ、 アクセス頻度:多で、HTTP 429エラーとなりました。

そこで、計測に使用するサーバを cloudflare に変更。

#requires -Version 5.1
#requires -RunAsAdministrator

$ErrorActionPreference = "Stop"

# ============================================================================
# 設定
# ============================================================================

$WifiAdapterName = "Wi-Fi"
$EthernetAdapterName = "イーサネット 4"

$WifiProfiles = @(
    "ないしょSSID1",
    "ないしょSSID2",
    "ないしょSSID3"
)

$RepeatCount = 3
$ConnectTimeoutSeconds = 20
$InternetTimeoutSeconds = 20
$IntervalSeconds = 30
$ConnectionStabilizeSeconds = 10

# Cloudflareからダウンロードするサイズ
$CloudflareDownloadBytes = 50000000

$CloudflareDownloadUrl = (
    "https://speed.cloudflare.com/__down?bytes=" +
    $CloudflareDownloadBytes
)

$CloudflareReferer = "https://speed.cloudflare.com/"

$CurlConnectTimeoutSeconds = 10
$CurlMaximumTimeSeconds = 180

$CsvFile = Join-Path $PSScriptRoot "speedtest.csv"
$LogFile = Join-Path $PSScriptRoot "speedtest-task.log"

$script:Results = @()
$script:ResultsSaved = $false
$script:TranscriptStarted = $false

# CSVに保存する列は、この5項目だけ
$CsvColumns = @(
    "Timestamp",
    "SSID",
    "Status",
    "DownloadMbps",
    "Message"
)


# ============================================================================
# 現在接続中のSSIDを取得
# ============================================================================

function Get-CurrentSsid {

    $lines = @(
        netsh.exe wlan show interfaces 2>&1
    )

    foreach ($item in $lines) {

        $line = $item.ToString()

        # BSSIDを拾わないように、行頭からSSIDを判定
        if ($line -match '^\s*SSID\s*:\s*(.*)$') {

            return $Matches[1].Trim()
        }
    }

    return ""
}


# ============================================================================
# 指定SSIDへの接続を待機
# ============================================================================

function Wait-ForSsid {

    param(
        [Parameter(Mandatory = $true)]
        [string]$ExpectedSsid,

        [Parameter(Mandatory = $true)]
        [int]$TimeoutSeconds
    )

    for (
        $second = 1;
        $second -le $TimeoutSeconds;
        $second++
    ) {

        Start-Sleep -Seconds 1

        $current = Get-CurrentSsid

        Write-Host (
            "Waiting for SSID [{0}/{1}]: Expected={2} Current={3}" -f
            $second,
            $TimeoutSeconds,
            $ExpectedSsid,
            $current
        )

        if ($current -eq $ExpectedSsid) {

            return $true
        }
    }

    return $false
}


# ============================================================================
# Wi-Fi切断
#
# Wi-Fiアダプター自体は無効化しない
# ============================================================================

function Disconnect-Wifi {

    param(
        [Parameter(Mandatory = $true)]
        [string]$InterfaceName
    )

    Write-Host "Disconnecting Wi-Fi: $InterfaceName"

    $oldPreference = $ErrorActionPreference
    $ErrorActionPreference = "Continue"

    try {

        $output = @(
            netsh.exe wlan disconnect `
                interface="$InterfaceName" 2>&1
        )

        $exitCode = $LASTEXITCODE
    }
    finally {

        $ErrorActionPreference = $oldPreference
    }

    foreach ($line in $output) {

        Write-Host $line.ToString()
    }

    Write-Host "netsh disconnect exit code: $exitCode"

    return ($exitCode -eq 0)
}


# ============================================================================
# Wi-Fi接続
#
# ProfileNameはWindowsに登録済みのWLANプロファイル名
# ============================================================================

function Connect-Wifi {

    param(
        [Parameter(Mandatory = $true)]
        [string]$ProfileName,

        [Parameter(Mandatory = $true)]
        [string]$InterfaceName
    )

    Write-Host "Requesting WLAN connection:"
    Write-Host "  Profile   : $ProfileName"
    Write-Host "  Interface : $InterfaceName"

    $oldPreference = $ErrorActionPreference
    $ErrorActionPreference = "Continue"

    try {

        $output = @(
            netsh.exe wlan connect `
                name="$ProfileName" `
                interface="$InterfaceName" 2>&1
        )

        $exitCode = $LASTEXITCODE
    }
    finally {

        $ErrorActionPreference = $oldPreference
    }

    foreach ($line in $output) {

        Write-Host $line.ToString()
    }

    Write-Host "netsh connect exit code: $exitCode"

    return ($exitCode -eq 0)
}


# ============================================================================
# TCP接続確認
# ============================================================================

function Test-TcpPort {

    param(
        [Parameter(Mandatory = $true)]
        [string]$HostName,

        [Parameter(Mandatory = $true)]
        [int]$Port,

        [Parameter(Mandatory = $true)]
        [int]$TimeoutMilliseconds
    )

    $client = New-Object System.Net.Sockets.TcpClient

    try {

        $task = $client.ConnectAsync(
            $HostName,
            $Port
        )

        if ($task.Wait($TimeoutMilliseconds)) {

            return $client.Connected
        }

        return $false
    }
    catch {

        return $false
    }
    finally {

        $client.Dispose()
    }
}


# ============================================================================
# インターネット接続待機
# ============================================================================

function Wait-ForInternet {

    param(
        [Parameter(Mandatory = $true)]
        [int]$TimeoutSeconds
    )

    $stopwatch = (
        [System.Diagnostics.Stopwatch]::StartNew()
    )

    $attempt = 0

    try {

        while (
            $stopwatch.Elapsed.TotalSeconds -lt
            $TimeoutSeconds
        ) {

            $attempt++

            $connected = Test-TcpPort `
                -HostName "speed.cloudflare.com" `
                -Port 443 `
                -TimeoutMilliseconds 1000

            $elapsed = [System.Math]::Round(
                $stopwatch.Elapsed.TotalSeconds,
                1
            )

            if ($connected) {

                Write-Host (
                    "Internet connection ready after {0}s." -f
                    $elapsed
                )

                return $true
            }

            Write-Host (
                "Waiting for Internet " +
                "[attempt {0}, {1}s/{2}s]" -f
                $attempt,
                $elapsed,
                $TimeoutSeconds
            )

            Start-Sleep -Milliseconds 500
        }

        return $false
    }
    finally {

        $stopwatch.Stop()
    }
}


# ============================================================================
# 結果をメモリーに追加
# ============================================================================

function Add-Result {

    param(
        [Parameter(Mandatory = $true)]
        [string]$Ssid,

        [Parameter(Mandatory = $true)]
        [string]$Status,

        [hashtable]$Values = @{}
    )

    $record = [ordered]@{}

    foreach ($column in $CsvColumns) {

        $record[$column] = $null
    }

    $record["Timestamp"] = (
        Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    )

    $record["SSID"] = $Ssid
    $record["Status"] = $Status

    foreach ($key in $Values.Keys) {

        if ($record.Contains($key)) {

            $record[$key] = $Values[$key]
        }
    }

    $script:Results += [PSCustomObject]$record
}


# ============================================================================
# Cloudflareダウンロード速度測定
# ============================================================================

function Invoke-CloudflareSpeedtest {

    $tempFileName = (
        "cloudflare-speedtest-{0}.bin" -f
        [System.Guid]::NewGuid().ToString("N")
    )

    $tempFile = Join-Path `
        -Path $env:TEMP `
        -ChildPath $tempFileName

    $stopwatch = $null
    $exitCode = $null
    $output = @()

    try {

        Write-Host "Cloudflare download URL:"
        Write-Host "  $CloudflareDownloadUrl"

        Write-Host "Temporary file:"
        Write-Host "  $tempFile"

        $oldPreference = $ErrorActionPreference
        $ErrorActionPreference = "Continue"

        try {

            $stopwatch = (
                [System.Diagnostics.Stopwatch]::StartNew()
            )

            $output = @(
                & curl.exe `
                    --ssl-no-revoke `
                    --silent `
                    --show-error `
                    --fail `
                    --location `
                    --connect-timeout $CurlConnectTimeoutSeconds `
                    --max-time $CurlMaximumTimeSeconds `
                    --header "Referer: $CloudflareReferer" `
                    --output $tempFile `
                    $CloudflareDownloadUrl 2>&1
            )

            $exitCode = $LASTEXITCODE
        }
        finally {

            if (
                ($null -ne $stopwatch) -and
                $stopwatch.IsRunning
            ) {

                $stopwatch.Stop()
            }

            $ErrorActionPreference = $oldPreference
        }

        $outputLines = @(
            $output |
                ForEach-Object {

                    $_.ToString()
                }
        )

        if ($exitCode -ne 0) {

            $errorText = $outputLines -join " "

            if (
                [System.String]::IsNullOrWhiteSpace(
                    $errorText
                )
            ) {

                $errorText = "No error output was returned."
            }

            throw (
                "Cloudflare download failed. " +
                "curl exit code $exitCode. " +
                "Output: $errorText"
            )
        }

        if (-not (Test-Path -LiteralPath $tempFile)) {

            throw "Cloudflare download file was not created."
        }

        $fileItem = Get-Item `
            -LiteralPath $tempFile `
            -ErrorAction Stop

        $size = [long]$fileItem.Length

        if ($size -le 0) {

            throw "Cloudflare downloaded file is empty."
        }

        $seconds = $stopwatch.Elapsed.TotalSeconds

        if ($seconds -le 0) {

            throw "Invalid download duration: $seconds"
        }

        $downloadMbpsValue = (
            [double]$size * 8.0
        ) / $seconds / 1000000.0

        $downloadMbps = [System.Math]::Round(
            $downloadMbpsValue,
            2
        )

        $downloadMegabytes = [System.Math]::Round(
            ([double]$size / 1MB),
            2
        )

        $elapsedSeconds = [System.Math]::Round(
            $seconds,
            3
        )

        return [PSCustomObject]@{
            DownloadMbps   = $downloadMbps
            DownloadBytes  = $size
            DownloadMB     = $downloadMegabytes
            ElapsedSeconds = $elapsedSeconds
        }
    }
    finally {

        if (
            ($null -ne $stopwatch) -and
            $stopwatch.IsRunning
        ) {

            $stopwatch.Stop()
        }

        if (Test-Path -LiteralPath $tempFile) {

            Remove-Item `
                -LiteralPath $tempFile `
                -Force `
                -ErrorAction SilentlyContinue
        }
    }
}


# ============================================================================
# CSV保存
# ============================================================================

function Save-Results {

    if ($script:ResultsSaved) {

        return
    }

    if ($script:Results.Count -eq 0) {

        Write-Warning "No test results were recorded."
        return
    }

    # ------------------------------------------------------------------------
    # 既存CSVのヘッダー確認
    #
    # 旧形式など、列が異なる場合は既存CSVを退避する
    # ------------------------------------------------------------------------

    if (Test-Path -LiteralPath $CsvFile) {

        $header = Get-Content `
            -LiteralPath $CsvFile `
            -TotalCount 1

        $expectedParts = @()

        foreach ($column in $CsvColumns) {

            $expectedParts += '"' + $column + '"'
        }

        $expectedHeader = $expectedParts -join ","

        if ($header -ne $expectedHeader) {

            $stamp = Get-Date -Format "yyyyMMdd-HHmmss"

            $directory = Split-Path -Parent $CsvFile

            $baseName = (
                [System.IO.Path]::GetFileNameWithoutExtension(
                    $CsvFile
                )
            )

            $oldFileName = (
                $baseName +
                "-old-" +
                $stamp +
                ".csv"
            )

            $oldFile = Join-Path `
                -Path $directory `
                -ChildPath $oldFileName

            Move-Item `
                -LiteralPath $CsvFile `
                -Destination $oldFile `
                -ErrorAction Stop

            Write-Warning (
                "CSV columns changed. " +
                "Old file moved to: $oldFile"
            )
        }
    }

    # ------------------------------------------------------------------------
    # CSVへ出力
    # ------------------------------------------------------------------------

    if (Test-Path -LiteralPath $CsvFile) {

        $script:Results |
            Select-Object $CsvColumns |
            Export-Csv `
                -LiteralPath $CsvFile `
                -NoTypeInformation `
                -Encoding UTF8 `
                -Append

        Write-Host "CSV appended: $CsvFile"
    }
    else {

        $script:Results |
            Select-Object $CsvColumns |
            Export-Csv `
                -LiteralPath $CsvFile `
                -NoTypeInformation `
                -Encoding UTF8

        Write-Host "CSV created: $CsvFile"
    }

    $script:ResultsSaved = $true
}


# ============================================================================
# Transcript開始
# ============================================================================

try {

    Start-Transcript `
        -LiteralPath $LogFile `
        -Append `
        -Force | Out-Null

    $script:TranscriptStarted = $true
}
catch {

    Write-Warning (
        "Could not start transcript: " +
        $_.Exception.Message
    )
}

# ============================================================================
# Wi-FiアダプターがDisabledの場合は終了
#
# このスクリプトではWi-Fiアダプターの
# Enable-NetAdapter / Disable-NetAdapterを実行しない
# ============================================================================

if ($wifiAdapter.Status -eq "Disabled") {

    throw (
        "Wi-Fi adapter '$WifiAdapterName' is disabled. " +
        "Turn Wi-Fi on before running this script."
    )
}

# ============================================================================
# 有線LANの元の状態を保存
# ============================================================================

$OriginalEthernetEnabled = (
    $ethernetAdapter.Status -ne "Disabled"
)

# ============================================================================
# メイン
# ============================================================================

try {

    # ========================================================================
    # 現在接続中のWi-Fiを切断
    #
    # Wi-Fiアダプター自体は無効化しない
    # ========================================================================

    Write-Host ""
    Write-Host "============================================================"
    Write-Host "Disconnecting current Wi-Fi connection"
    Write-Host "============================================================"

    $null = Disconnect-Wifi `
        -InterfaceName $WifiAdapterName

    Start-Sleep -Seconds 2


    # ========================================================================
    # 測定中は有線LANを無効化
    # ========================================================================

    Write-Host ""
    Write-Host "Disabling wired LAN..."

    Disable-NetAdapter `
        -Name $EthernetAdapterName `
        -Confirm:$false `
        -ErrorAction Stop

    Write-Host "Wired LAN disabled: $EthernetAdapterName"


    # ========================================================================
    # 各Wi-Fiプロファイルで測定
    # ========================================================================

    foreach ($wifi in $WifiProfiles) {

        Write-Host ""
        Write-Host "============================================================"
        Write-Host "Connecting to: $wifi"
        Write-Host "============================================================"

        try {

            # ----------------------------------------------------------------
            # 現在のWi-Fi接続を切断
            # ----------------------------------------------------------------

            $null = Disconnect-Wifi `
                -InterfaceName $WifiAdapterName

            Start-Sleep -Seconds 2


            # ----------------------------------------------------------------
            # 指定プロファイルへ接続
            # ----------------------------------------------------------------

            $connectResult = Connect-Wifi `
                -ProfileName $wifi `
                -InterfaceName $WifiAdapterName

            if (-not $connectResult) {

                $message = (
                    "netsh wlan connect command failed."
                )

                Write-Warning $message

                Add-Result `
                    -Ssid $wifi `
                    -Status "ConnectFailed" `
                    -Values @{
                        Message = $message
                    }

                continue
            }


            # ----------------------------------------------------------------
            # 指定SSIDへの接続完了を待機
            # ----------------------------------------------------------------

            $connected = Wait-ForSsid `
                -ExpectedSsid $wifi `
                -TimeoutSeconds $ConnectTimeoutSeconds

            if (-not $connected) {

                $current = Get-CurrentSsid

                $message = (
                    "Connection failed. " +
                    "Expected=$wifi Current=$current"
                )

                Write-Warning $message

                Add-Result `
                    -Ssid $wifi `
                    -Status "ConnectFailed" `
                    -Values @{
                        Message = $message
                    }

                continue
            }

            Write-Host "Connected to SSID: $wifi"


            # ----------------------------------------------------------------
            # インターネット接続を確認
            # ----------------------------------------------------------------

            $internetReady = Wait-ForInternet `
                -TimeoutSeconds $InternetTimeoutSeconds

            if (-not $internetReady) {

                $message = (
                    "Internet access unavailable on $wifi"
                )

                Write-Warning $message

                Add-Result `
                    -Ssid $wifi `
                    -Status "NoInternet" `
                    -Values @{
                        Message = $message
                    }

                continue
            }


            # ----------------------------------------------------------------
            # 接続安定待ち
            # ----------------------------------------------------------------

            Write-Host (
                "Waiting $ConnectionStabilizeSeconds seconds " +
                "for connection stabilization..."
            )

            Start-Sleep `
                -Seconds $ConnectionStabilizeSeconds


            # ----------------------------------------------------------------
            # Cloudflareダウンロード速度測定
            # ----------------------------------------------------------------

            for (
                $n = 1;
                $n -le $RepeatCount;
                $n++
            ) {

                Write-Host ""
                Write-Host (
                    "Cloudflare download test " +
                    "$n / $RepeatCount"
                )

                try {

                    # 測定直前に接続SSIDを再確認
                    $current = Get-CurrentSsid

                    if ($current -ne $wifi) {

                        throw (
                            "SSID changed. " +
                            "Expected=$wifi Current=$current"
                        )
                    }

                    $test = Invoke-CloudflareSpeedtest

                    $download = $test.DownloadMbps

                    Add-Result `
                        -Ssid $wifi `
                        -Status "OK" `
                        -Values @{
                            DownloadMbps = $download
                            Message      = ""
                        }

                    Write-Host ""
                    Write-Host "========== Result =========="

                    Write-Host (
                        "Downloaded : {0:N2} MB" -f
                        $test.DownloadMB
                    )

                    Write-Host (
                        "Time       : {0:N3} sec" -f
                        $test.ElapsedSeconds
                    )

                    Write-Host (
                        "Download   : {0:N2} Mbps" -f
                        $download
                    )
                }
                catch {

                    $message = $_.Exception.Message

                    Write-Warning (
                        "Cloudflare speed test failed: " +
                        $message
                    )

                    Add-Result `
                        -Ssid $wifi `
                        -Status "CloudflareTestFailed" `
                        -Values @{
                            Message = $message
                        }
                }

                if ($n -lt $RepeatCount) {

                    Write-Host (
                        "Waiting $IntervalSeconds seconds " +
                        "before next test..."
                    )

                    Start-Sleep `
                        -Seconds $IntervalSeconds
                }
            }
        }
        catch {

            $message = $_.Exception.Message

            Write-Warning (
                "Test failed for $wifi : $message"
            )

            Add-Result `
                -Ssid $wifi `
                -Status "Error" `
                -Values @{
                    Message = $message
                }
        }
        finally {

            # ================================================================
            # このSSIDの測定終了後に切断
            #
            # Wi-Fiアダプター自体は無効化しない
            # ================================================================

            Write-Host ""
            Write-Host "Disconnecting from: $wifi"

            try {

                $null = Disconnect-Wifi `
                    -InterfaceName $WifiAdapterName
            }
            catch {

                Write-Warning (
                    "Wi-Fi disconnect failed: " +
                    $_.Exception.Message
                )
            }

            Start-Sleep -Seconds 2
        }
    }

    # ========================================================================
    # 結果表示
    # ========================================================================

    Write-Host ""
    Write-Host "============================================================"
    Write-Host "Results"
    Write-Host "============================================================"

    if ($script:Results.Count -gt 0) {

        $script:Results |
            Format-Table `
                Timestamp,
                SSID,
                Status,
                DownloadMbps,
                Message `
                -AutoSize
    }

    Save-Results
}
finally {

    # ========================================================================
    # 未保存の結果がある場合はCSVへ保存
    # ========================================================================

    if (
        (-not $script:ResultsSaved) -and
        ($script:Results.Count -gt 0)
    ) {

        try {

            Save-Results
        }
        catch {

            Write-Warning (
                "CSV save failed: " +
                $_.Exception.Message
            )
        }
    }


    # ========================================================================
    # 最終Wi-Fi切断
    #
    # Wi-Fiアダプター自体は無効化しない
    # ========================================================================

    Write-Host ""
    Write-Host "============================================================"
    Write-Host "Disconnecting Wi-Fi"
    Write-Host "============================================================"

    try {

        $null = Disconnect-Wifi `
            -InterfaceName $WifiAdapterName

        Write-Host "Wi-Fi disconnected."
        Write-Host "Wi-Fi adapter remains enabled."
    }
    catch {

        Write-Warning (
            "Could not disconnect Wi-Fi: " +
            $_.Exception.Message
        )
    }


    # ========================================================================
    # 有線LANを元の状態へ復元
    # ========================================================================

    Write-Host ""
    Write-Host "============================================================"
    Write-Host "Restoring wired LAN state"
    Write-Host "============================================================"

    try {

        if ($OriginalEthernetEnabled) {

            Enable-NetAdapter `
                -Name $EthernetAdapterName `
                -Confirm:$false `
                -ErrorAction Stop

            Write-Host (
                "Wired LAN enabled: " +
                $EthernetAdapterName
            )
        }
        else {

            Disable-NetAdapter `
                -Name $EthernetAdapterName `
                -Confirm:$false `
                -ErrorAction SilentlyContinue

            Write-Host (
                "Wired LAN was originally disabled " +
                "and remains disabled."
            )
        }
    }
    catch {

        Write-Warning (
            "Could not restore wired LAN state: " +
            $_.Exception.Message
        )
    }

}

powershellから wifi速度をspeedtestで計測し、csvに保存

https://www.speedtest.net/ja を用い、wifi速度を計測する powershell (ps1)です。

PS> powershell -ExecutionPolicy Bypass -File .\speedtest.ps1

↓こう書いて、↑こう実行してください

#requires -Version 5.1
#requires -RunAsAdministrator

# Wi-Fi の速度計測スクリプト
# このファイルは UTF-8 (BOM 付き) で保存
# (BOM なしのファイルを Shift-JIS として読むため)
# speedtest.exe はこのスクリプトと同じフォルダに置く

$ErrorActionPreference = "Stop"

# -----------------------------------------------------------------------------
# 設定
# -----------------------------------------------------------------------------

$WifiAdapterName = "Wi-Fi"

# 有線 LAN のアダプタ名 (Get-NetAdapter で表示される名前)
$EthernetAdapterName = "イーサネット 4"

# 計測する WLAN プロファイル名 (netsh wlan show profiles で表示される名前)
$WifiProfiles = @(
    "ないしょ1",
    "ないしょ2"
    #"ないしょ3"
)

$RepeatCount = 3
$ConnectTimeoutSeconds = 10
$InternetTimeoutSeconds = 10
$IntervalSeconds = 5

$SpeedtestExe = Join-Path $PSScriptRoot "speedtest.exe"
$CsvFile = Join-Path $PSScriptRoot "speedtest.csv"
$Results = @()
$script:ResultsSaved = $false

# CSV の列 (この順で出力する。全レコードがすべての列を持つ)
$CsvColumns = @(
    "Timestamp",         # 記録日時 (yyyy-MM-dd HH:mm:ss)
    "SSID",              # 計測対象の SSID ($WifiProfiles の値)
    "Status",            # 結果: OK / ConnectFailed / NoInternet / SpeedtestFailed / Error
    "DownloadMbps",      # 下り速度 (Mbps)
    "UploadMbps",        # 上り速度 (Mbps)
    "LatencyMs",         # 応答時間 (Ping, ミリ秒)
    "PacketLossPercent", # パケットロス率 (%)。サーバーが測定できない場合は空
    "Server"             # 計測に使ったサーバー名
)

# -----------------------------------------------------------------------------
# 関数
# -----------------------------------------------------------------------------

function Get-CurrentSsid {
    $lines = @(netsh wlan show interfaces 2>&1)

    foreach ($item in $lines) {
        $line = $item.ToString()

        if ($line -match '^\s*SSID\s*:\s*(.*)$') {
            return $Matches[1].Trim()
        }
    }

    return ""
}

function Wait-ForSsid {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ExpectedSsid,

        [Parameter(Mandatory = $true)]
        [int]$TimeoutSeconds
    )

    for ($second = 1; $second -le $TimeoutSeconds; $second++) {
        Start-Sleep -Seconds 1
        $current = Get-CurrentSsid
        Write-Host "Waiting for SSID [$second/$TimeoutSeconds]: $current"

        if ($current -eq $ExpectedSsid) {
            return $true
        }
    }

    return $false
}

function Test-TcpPort {
    param(
        [Parameter(Mandatory = $true)]
        [string]$HostName,

        [Parameter(Mandatory = $true)]
        [int]$Port,

        [Parameter(Mandatory = $true)]
        [int]$TimeoutMilliseconds
    )

    $client = New-Object System.Net.Sockets.TcpClient

    try {
        $task = $client.ConnectAsync($HostName, $Port)

        if ($task.Wait($TimeoutMilliseconds)) {
            return $client.Connected
        }

        return $false
    }
    catch {
        return $false
    }
    finally {
        $client.Dispose()
    }
}

function Wait-ForInternet {
    param(
        [Parameter(Mandatory = $true)]
        [int]$TimeoutSeconds
    )

    # 試行回数ではなく経過時間で打ち切る。失敗に時間がかかっても、
    # 待ち時間が $TimeoutSeconds を大きく超えないようにするため。
    $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
    $attempt = 0

    while ($stopwatch.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
        $attempt++

        $ok = Test-TcpPort `
            -HostName "www.speedtest.net" `
            -Port 443 `
            -TimeoutMilliseconds 1000

        if ($ok) {
            return $true
        }

        $elapsed = [math]::Round($stopwatch.Elapsed.TotalSeconds, 1)
        Write-Host "Waiting for Internet [attempt $attempt, ${elapsed}s/${TimeoutSeconds}s]"
        Start-Sleep -Milliseconds 500
    }

    return $false
}

function Add-Result {
    param(
        [Parameter(Mandatory = $true)]
        [string]$Ssid,

        [Parameter(Mandatory = $true)]
        [string]$Status,

        [hashtable]$Values = @{}
    )

    $record = [ordered]@{}

    foreach ($column in $CsvColumns) {
        $record[$column] = $null
    }

    $record["Timestamp"] = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $record["SSID"] = $Ssid
    $record["Status"] = $Status

    foreach ($key in $Values.Keys) {
        $record[$key] = $Values[$key]
    }

    $script:Results += [PSCustomObject]$record
}

function Invoke-Speedtest {
    # speedtest.exe は stderr に警告を出すことがある。PowerShell 5.1 では
    # $ErrorActionPreference = "Stop" のとき stderr の出力が例外になるため、
    # この呼び出しの間だけ "Continue" にする。
    $previousPreference = $ErrorActionPreference
    $ErrorActionPreference = "Continue"

    try {
        $output = @(
            & $SpeedtestExe `
                --accept-license `
                --accept-gdpr `
                --format=json 2>&1
        )
        $exitCode = $LASTEXITCODE
    }
    finally {
        $ErrorActionPreference = $previousPreference
    }

    $stdoutLines = @(
        $output | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] } |
            ForEach-Object { $_.ToString() }
    )

    $stderrLines = @(
        $output | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] } |
            ForEach-Object { $_.ToString() }
    )

    if ($exitCode -ne 0) {
        $errorText = (@($stderrLines) + @($stdoutLines)) -join " "
        throw "Speedtest exit code $exitCode. Output: $errorText"
    }

    # JSON の type が "result" の行を結果として使う (ログ行は無視する)
    foreach ($line in $stdoutLines) {
        if ([string]::IsNullOrWhiteSpace($line)) {
            continue
        }

        try {
            $json = $line | ConvertFrom-Json
        }
        catch {
            continue
        }

        if ($json.type -eq "result") {
            return $json
        }
    }

    $allText = (@($stdoutLines) + @($stderrLines)) -join " "
    throw "Speedtest returned no result. Output: $allText"
}

# Wi-Fi のオン/オフ (設定画面の Wi-Fi トグルと同じ) を WinRT で切り替える。
# アダプタが無効だと無線 (Radio) が見つからないため、先に有効化しておくこと。
Add-Type -AssemblyName System.Runtime.WindowsRuntime

$script:AsTaskGeneric = [System.WindowsRuntimeSystemExtensions].GetMethods() |
    Where-Object {
        $_.Name -eq 'AsTask' -and
        $_.GetParameters().Count -eq 1 -and
        $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1'
    } |
    Select-Object -First 1

[Windows.Devices.Radios.Radio, Windows.System.Devices, ContentType = WindowsRuntime] | Out-Null

function Wait-WinRtTask {
    param(
        [Parameter(Mandatory = $true)]
        $Operation,

        [Parameter(Mandatory = $true)]
        [Type]$ResultType
    )

    $task = $script:AsTaskGeneric.MakeGenericMethod($ResultType).Invoke($null, @($Operation))
    $task.Wait(-1) | Out-Null
    return $task.Result
}

function Get-WifiRadio {
    $access = Wait-WinRtTask `
        -Operation ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) `
        -ResultType ([Windows.Devices.Radios.RadioAccessStatus])

    if ($access -ne [Windows.Devices.Radios.RadioAccessStatus]::Allowed) {
        throw "Radio access denied: $access"
    }

    $radios = Wait-WinRtTask `
        -Operation ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) `
        -ResultType ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])

    $radio = $radios |
        Where-Object { $_.Kind -eq [Windows.Devices.Radios.RadioKind]::WiFi } |
        Select-Object -First 1

    if ($null -eq $radio) {
        throw "Wi-Fi radio not found"
    }

    return $radio
}

function Set-WifiRadio {
    param(
        [Parameter(Mandatory = $true)]
        [ValidateSet('On', 'Off')]
        [string]$State
    )

    $radio = Get-WifiRadio

    $status = Wait-WinRtTask `
        -Operation ($radio.SetStateAsync([Windows.Devices.Radios.RadioState]::$State)) `
        -ResultType ([Windows.Devices.Radios.RadioAccessStatus])

    if ($status -ne [Windows.Devices.Radios.RadioAccessStatus]::Allowed) {
        throw "Could not turn Wi-Fi $State : $status"
    }
}

function Save-Results {
    if ($script:ResultsSaved) {
        return
    }

    if ($Results.Count -eq 0) {
        Write-Warning "No test results were recorded."
        return
    }

    if (Test-Path -LiteralPath $CsvFile) {
        # 列構成が違うと Export-Csv -Append が失敗するため、
        # 旧形式のファイルは退避して新しく作り直す。
        $header = Get-Content -LiteralPath $CsvFile -TotalCount 1
        $expected = ($CsvColumns | ForEach-Object { '"' + $_ + '"' }) -join ","

        if ($header -ne $expected) {
            $stamp = Get-Date -Format "yyyyMMdd-HHmmss"
            $oldFile = Join-Path `
                (Split-Path -Parent $CsvFile) `
                ([IO.Path]::GetFileNameWithoutExtension($CsvFile) + "-old-$stamp.csv")
            Move-Item -LiteralPath $CsvFile -Destination $oldFile
            Write-Warning "CSV columns changed. Old file moved to: $oldFile"
        }
    }

    if (Test-Path -LiteralPath $CsvFile) {
        $Results | Export-Csv `
            -Path $CsvFile `
            -NoTypeInformation `
            -Encoding UTF8 `
            -Append

        Write-Host "CSV appended: $CsvFile"
    }
    else {
        $Results | Export-Csv `
            -Path $CsvFile `
            -NoTypeInformation `
            -Encoding UTF8

        Write-Host "CSV created: $CsvFile"
    }

    $script:ResultsSaved = $true
}

# -----------------------------------------------------------------------------
# 事前チェック
# -----------------------------------------------------------------------------

if (-not (Test-Path -LiteralPath $SpeedtestExe)) {
    throw "speedtest.exe not found: $SpeedtestExe"
}

$wifiAdapter = Get-NetAdapter `
    -Name $WifiAdapterName `
    -ErrorAction Stop

$ethernetAdapter = Get-NetAdapter `
    -Name $EthernetAdapterName `
    -ErrorAction Stop

Write-Host "Wi-Fi adapter : $($wifiAdapter.Name)"
Write-Host "LAN adapter   : $($ethernetAdapter.Name)"
Write-Host "LAN device    : $($ethernetAdapter.InterfaceDescription)"

# 終了時に元へ戻すため、実行前の状態を記録しておく
$OriginalEthernetEnabled = ($ethernetAdapter.Status -ne "Disabled")
$OriginalWifiRadioOn = $false
$OriginalSsid = ""

if ($wifiAdapter.Status -ne "Disabled") {
    try {
        $OriginalWifiRadioOn = ((Get-WifiRadio).State -eq [Windows.Devices.Radios.RadioState]::On)
    }
    catch {
        Write-Warning "Could not read Wi-Fi radio state: $($_.Exception.Message)"
    }

    if ($OriginalWifiRadioOn) {
        $OriginalSsid = Get-CurrentSsid
    }
}

Write-Host "Original state: LAN enabled=$OriginalEthernetEnabled, Wi-Fi on=$OriginalWifiRadioOn, SSID=$OriginalSsid"

# -----------------------------------------------------------------------------
# メイン処理
# -----------------------------------------------------------------------------

try {
    Write-Host ""
    Write-Host "Disabling wired LAN..."
    Disable-NetAdapter `
        -Name $EthernetAdapterName `
        -Confirm:$false

    Write-Host "Enabling Wi-Fi adapter..."
    Enable-NetAdapter `
        -Name $WifiAdapterName `
        -Confirm:$false

    Start-Sleep -Seconds 3

    Write-Host "Turning Wi-Fi on..."
    Set-WifiRadio -State On

    Start-Sleep -Seconds 3

    foreach ($wifi in $WifiProfiles) {
        Write-Host ""
        Write-Host "========================================"
        Write-Host "Connecting to: $wifi"
        Write-Host "========================================"

        try {
            netsh wlan connect name="$wifi" | Out-Host

            $connected = Wait-ForSsid `
                -ExpectedSsid $wifi `
                -TimeoutSeconds $ConnectTimeoutSeconds

            if (-not $connected) {
                $current = Get-CurrentSsid
                $message = "Connection failed. Expected=$wifi Current=$current"
                Write-Warning $message
                Add-Result -Ssid $wifi -Status "ConnectFailed"
                continue
            }

            $internetReady = Wait-ForInternet `
                -TimeoutSeconds $InternetTimeoutSeconds

            if (-not $internetReady) {
                $message = "Internet access unavailable on $wifi"
                Write-Warning $message
                Add-Result -Ssid $wifi -Status "NoInternet"
                continue
            }

            for ($n = 1; $n -le $RepeatCount; $n++) {
                Write-Host ""
                Write-Host "Speedtest $n / $RepeatCount"

                try {
                    $current = Get-CurrentSsid

                    if ($current -ne $wifi) {
                        throw "SSID changed to $current"
                    }

                    $test = Invoke-Speedtest

                    $download = [math]::Round(
                        (([double]$test.download.bandwidth * 8.0) / 1000000.0),
                        2
                    )

                    $upload = [math]::Round(
                        (([double]$test.upload.bandwidth * 8.0) / 1000000.0),
                        2
                    )

                    $latency = [math]::Round(
                        [double]$test.ping.latency,
                        2
                    )

                    # サーバーがパケットロスを測定できない場合、packetLoss は存在しない
                    $packetLoss = $null

                    if ($null -ne $test.packetLoss) {
                        $packetLoss = [math]::Round([double]$test.packetLoss, 2)
                    }

                    Add-Result -Ssid $wifi -Status "OK" -Values @{
                        DownloadMbps      = $download
                        UploadMbps        = $upload
                        LatencyMs         = $latency
                        PacketLossPercent = $packetLoss
                        Server            = $test.server.name
                    }

                    Write-Host "Download   : $download Mbps"
                    Write-Host "Upload     : $upload Mbps"
                    Write-Host "Ping       : $latency ms"
                    Write-Host "PacketLoss : $packetLoss %"
                    Write-Host "Server     : $($test.server.name) (id $($test.server.id))"
                }
                catch {
                    $message = $_.Exception.Message
                    Write-Warning "Speedtest failed: $message"
                    Add-Result -Ssid $wifi -Status "SpeedtestFailed"
                }

                if ($n -lt $RepeatCount) {
                    Start-Sleep -Seconds $IntervalSeconds
                }
            }
        }
        catch {
            $message = $_.Exception.Message
            Write-Warning "Test failed for $wifi : $message"
            Add-Result -Ssid $wifi -Status "Error"
        }
    }

    Write-Host ""
    Write-Host "========================================"
    Write-Host "Results"
    Write-Host "========================================"

    if ($Results.Count -gt 0) {
        $Results | Format-Table `
            SSID, `
            Status, `
            DownloadMbps, `
            UploadMbps, `
            LatencyMs, `
            PacketLossPercent `
            -AutoSize
    }

    Save-Results
}
finally {
    if (-not $script:ResultsSaved -and $Results.Count -gt 0) {
        try {
            Save-Results
        }
        catch {
            Write-Warning "CSV save failed: $($_.Exception.Message)"
        }
    }

    Write-Host ""
    Write-Host "Restoring network state..."

    # Wi-Fi アダプタは有効のまま残し、オン/オフだけを元に戻す
    try {
        if ($OriginalWifiRadioOn) {
            Set-WifiRadio -State On
            Write-Host "Wi-Fi left on."

            if ($OriginalSsid -ne "" -and (Get-CurrentSsid) -ne $OriginalSsid) {
                # プロファイル名と SSID が同じであることを前提にしている
                netsh wlan connect name="$OriginalSsid" | Out-Host
            }
        }
        else {
            Set-WifiRadio -State Off
            Write-Host "Wi-Fi turned off."
        }
    }
    catch {
        Write-Warning "Could not restore Wi-Fi: $($_.Exception.Message)"
    }

    if ($OriginalEthernetEnabled) {
        try {
            Enable-NetAdapter `
                -Name $EthernetAdapterName `
                -Confirm:$false `
                -ErrorAction Stop

            Write-Host "Wired LAN enabled: $EthernetAdapterName"
        }
        catch {
            Write-Warning "Could not enable wired LAN: $($_.Exception.Message)"
        }
    }
    else {
        Write-Host "Wired LAN left disabled (it was disabled before the test)."
    }
}

emacsのフッタ(mode line)に文字コード名を表示

powershellのps1ファイルに、日本語で記載する際、 文字コードを"bom付きutf-8"とすることで、windowsが日本語として認識します。

通常、emacsのフッタ(mode line)での文字コードは、 UやSなど、1文字のみで表示される為、BOMの有無は不明です。

しかし、init.elに以下の記載を追加すると、 emacsのフッタ(mode line)に文字コード名を表示できます

(setq-default mode-line-misc-info
  (append mode-line-misc-info
    '((:eval
        (when buffer-file-name
          (format " [%s]"
            buffer-file-coding-system))))))

以下は、「文字コード:BOM付きUTF-8 」での表示例です

ubuntu on wsl2 を用いた win11内への claude code用sandbox

ubuntu-26.04のinstall

既に oracle linuxをinstall済ですが、今回、ubuntuを追加

CMD> wsl --list
Linux 用 Windows サブシステム ディストリビューション:
OracleLinux_9_5 (既定値)
CMD> wsl --list --online
NAME                            FRIENDLY NAME
Ubuntu                          Ubuntu
Ubuntu-26.04                    Ubuntu 26.04 LTS
Ubuntu-24.04                    Ubuntu 24.04 LTS
  :
  
CMD> wsl --install Ubuntu-26.04
  :
Create a default Unix user account: end0t
New password:
Retype new password:
  :

※ Ubuntuへの情報提供はNO
Would you like to opt-in to platform metrics collection (Y/n)? To see an example of the data collected, enter 'e'.
[Y/n/e]: n

wslのubuntu再起動

CMD> wsl --shutdown
CMD> wsl -d Ubuntu-26.04

claude code、関連packageのinstall

$ sudo apt update && sudo apt install -y squid iptables curl jq
$ curl -fsSL https://claude.ai/install.sh | bash

$ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc && source ~/.bashrc

$ which claude
/home/end0t/.local/bin/claude

$ claude --version
2.1.310 (Claude Code)

squid で許可ドメインを設定

originalのsquid.confを以下の内容で書換え、 ubuntuから外部へのアクセスを claude関連に限定

$ sudo cp /etc/squid/squid.conf /etc/squid/squid.conf.org

$ sudo vi /etc/squid/squid.conf

http_port 127.0.0.1:3128

acl allowed_domains dstdomain .anthropic.com .claude.ai claude.ai
acl SSL_ports port 443
acl CONNECT method CONNECT

http_access deny CONNECT !SSL_ports
http_access allow CONNECT allowed_domains
http_access deny all

cache deny all
$ sudo systemctl enable squid
$ sudo systemctl restart squid

firewall.sh 新規作成

$ sudo vi /usr/local/sbin/firewall.sh

#!/bin/sh
iptables -F OUTPUT
iptables -P OUTPUT DROP
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m owner --uid-owner proxy -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -m owner --uid-owner proxy -p tcp --dport 53 -j ACCEPT
iptables -A OUTPUT -m owner --uid-owner proxy -p tcp --dport 443 -j ACCEPT

ip6tables -F OUTPUT
ip6tables -P OUTPUT DROP
ip6tables -A OUTPUT -o lo -j ACCEPT

$ sudo chmod 755 /usr/local/sbin/firewall.sh

/etc/wsl.conf編集

マウント・連携の無効化と起動時処理

$ sudo vi /etc/wsl.conf

[boot]
systemd=true
command="/usr/local/sbin/firewall.sh"

[automount]
enabled=false
mountFsTab=false

[interop]
enabled=false
appendWindowsPath=false

[user]
default=end0t

作業ユーザから sudo を外す

$ sudo deluser end0t sudo

.bashrcに claude code 用 環境変数 追記

$ vi ~/.bashrc

export HTTPS_PROXY=http://127.0.0.1:3128
export HTTP_PROXY=http://127.0.0.1:3128
export DISABLE_AUTOUPDATER=1
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1

動作テスト

wsl再起動

CMD> wsl --shutdown
CMD> wsl -d Ubuntu-26.04

安全であることを確認

$ ls /mnt/c                        # 存在しない、または空
$ cmd.exe                          # command not found
$ curl -m 5 https://www.google.com # 失敗する(プロキシで拒否)
$ curl -m 5 --noproxy '*' https://api.anthropic.com  # 失敗する(直接通信は遮断)

claude起動

初回起動時、画面の案内に従い、claudeへのログイン要

$ claude

その他

rootでのwsl起動

CMD> wsl -d Ubuntu-26.04 -u root

claude codeのコマンド

win版のclaude codeと画面構成がかなり異なる為

/resume      # 他のセッションへの切替え
/clear      # 新規セッションへの切替え

coacd for python を用い、STEPファイルを、矩形STLに分解&変換

MuJoCoを用いたロボットのシミュレーションを考えていますが、 MuJoCoが扱えるのはSTL形式で、また、当たり判定用に凹凸のあるソリッドは、 矩形に分解する必要があるらしい。

これを受け、coacd も用い、次のように実装

"""STEPファイルに含まれる部材を部材毎のSTLファイルに出力する。
ただし、MuJoCoでのシミュレーションを行う際の当たり判定用に
凹凸があるスラブは分割。"""
import argparse
import json
import re
from pathlib import Path

import coacd      # 凸分解 library (pip install coacd)
import gmsh       # STEP 読込みと、表面の三角形分割。内部で OpenCASCADEを使用
import numpy as np
import trimesh    # 三角形メッシュの操作 (法線の向きの修正、STL の読み書き)

# ---- 設定 ----
SCALE = 0.2       # 縮尺 (1/5 の縮小模型)
MESH_SIZE = 50.0  # 三角形の細かさ: 実寸での最大メッシュ辺長 [mm]
GROUND_TOL = 1.0  # 底面区分の判定 [mm]

# MuJoCoでのシミュレーションを行う際、長辺方向をY軸に沿わす為
R_WORLD = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]], float)


def load_solids(step: Path, mesh_size: float):
    """STEP 内にある各solidを (名前, 頂点座標, 頂点番号) で返す """
    ret_solids = []
    try:
        gmsh.initialize()
        gmsh.option.setNumber("General.Terminal", 0)  # 進捗を非表示
        gmsh.option.setString("Geometry.OCCTargetUnit", "MM")  # 単位 mm
        
        gmsh.model.occ.importShapes(str(step))  # STEP の全solidを読み込む
        gmsh.model.occ.synchronize()            # 読込んだ形を gmsh型に反映
        # 曲面は円周を 24 分割。360/24=15度
        # 平らな面でも 1 辺が mesh_size [mm] を超えないようにする
        gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 24)
        
        gmsh.option.setNumber("Mesh.MeshSizeMax", mesh_size)
        
        # 表面だけを三角形に分割。
        # 例 generate(1):辺に分割、generate(2):面に分割、generate(3):立体に分割
        gmsh.model.mesh.generate(2)

        # 全頂点の番号と座標。ただし、[x0,y0,z0, x1,y1,z1, ...] の 1次元配列化
        node_tags, coords, _ = gmsh.model.mesh.getNodes()
        index = {t: i for i, t in enumerate(node_tags)}
        coords = coords.reshape(-1, 3)

        # gmsh.model.getEntities(3)で、全solidの次元数と番号を取得し、for-loop
        for dim, tag in gmsh.model.getEntities(3):
            surfs = [] # 表面番号を収集
            for _, s in gmsh.model.getBoundary([(dim, tag)], oriented=False):
                surfs.append( abs(s) )
                
            # 各表面の 3節点三角形を取出す
            nodes = []
            for s in surfs:
                _, node_tags = gmsh.model.mesh.getElementsByType(2, s)
                nodes.extend(node_tags)
            tris = np.array(nodes).reshape(-1, 3)

            # このsolidで使用する節点だけを取り、番号を 0 から振り直す
            used, inverse = np.unique(tris, return_inverse=True)
            verts = coords[[index[t] for t in used]]

            solid = (gmsh.model.getEntityName(dim, tag),
                     verts,
                     inverse.reshape(-1, 3) )
            ret_solids.append( solid )
    except Exception as e:
        print( e )
        
    gmsh.finalize()
    return ret_solids


def code_of(path_name: str) -> str:
    """名前から品番抽出 (stlのfile名に付けるため) """
    leaf = path_name.rsplit("/", 1)[-1]
    m = re.match(r"\(\d+\)\s+(\S+)", leaf)
    return m.group(1) if m else ""


def coacd_decompose(src: Path, out_dir: Path, threshold: float = 0.02) -> int:
    """当たり判定用に STL を凸分解し、2 つ以上なら out_dir に各STLを保存"""

    mesh = trimesh.load(src, force="mesh")
    coacd.set_log_level("error")  # 途中経過の表示を止める (エラーだけ出す)
    
    # 凸分解の本体。時間がかかるのはココ
    parts = coacd.run_coacd(coacd.Mesh(mesh.vertices, mesh.faces),
                            threshold=threshold)
    
    if out_dir.exists():
        for old in out_dir.glob("*.stl"):
            old.unlink()
        out_dir.rmdir()
    if len(parts) == 1:  # 分解されない場合
        return 1
    
    out_dir.mkdir(parents=True)
    for i, (v, f) in enumerate(parts):
        trimesh.Trimesh(v, f).export(out_dir / f"{src.stem}_c{i:03d}.stl")
    return len(parts)


def main():
    p = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("step",type=Path, help="変換元 STEP ファイル")
    p.add_argument("out", type=Path, help="出力先 STL フォルダ (なければ作成)")
    args = p.parse_args()
    step = args.step
    if not step.exists():
        p.error(f"STEP ファイルがありません: {step}")  # usageを表示し終了

    out = args.out
    out.mkdir(parents=True, exist_ok=True)
    
    solids = load_solids(step, MESH_SIZE)

    # 全部材の頂点から、中心座標を算出
    all_v = np.vstack([v for _, v, _ in solids])
    lo, hi = all_v.min(axis=0), all_v.max(axis=0)
    center = np.array([(lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2, 0.0])

    # 組立品のいちばん低い高さから区分の判定に使う
    ground_z = lo[2] * SCALE

    members = []
    for i, (path_name, verts, faces) in enumerate(solids):
        # 全solidの中心を原点にし、ワールドの向きに回して、縮小
        v = (verts - center) @ R_WORLD.T * SCALE
        vlo, vhi = v.min(axis=0), v.max(axis=0)  # この部材を囲む箱
        
        # 設置位置 (底面中心)
        pos = np.array([(vlo[0] + vhi[0]) / 2, (vlo[1] + vhi[1]) / 2, vlo[2]])
        size = vhi - vlo
        
        # 「土台」は、MuJoCoで固定部材として扱うため
        group = "土台" if vlo[2] - ground_z < GROUND_TOL else "その他"
        
        code = code_of(path_name)
        name = f"no{i:02d}_{code}" if code else f"no{i:02d}"

        # meshの原点を部材の底面中心に移す。
        # process=True で、重なった頂点をまとめる(整理をする)
        mesh = trimesh.Trimesh(v - pos, faces, process=True)
        # 三角形の表裏 (法線の向き) を外向きにそろえる
        #(向きがばらばらだと、体積や質量の計算がおかしくなる)
        trimesh.repair.fix_normals(mesh)
        # STLファイルとして保存
        mesh.export(out / f"{name}.stl")
        
        # 当たり判定用に 凸分解
        n_parts = coacd_decompose(out / f"{name}.stl", out / name)
        
        # MuJoCo 単位は mの為、mm → m に直して記録
        members.append(
            dict(name=name,
                 group=group,
                 pos=(pos / 1000).round(6).tolist(),  # 設置位置(底面中心)
                 size=(size / 1000).round(6).tolist(),# 寸法
                 long_axis="x" if size[0] >= size[1] else "y",  # 長手方向
                 parts=n_parts) )       # 当たり判定の凸の部品の数
        print(f"{name:20s} {group} 寸法 {size.round(1)} mm  凸パーツ {n_parts}")

    # 部材の一覧を JSON で書く。
    # ensure_ascii=False で日本語をそのまま書く (\uXXXX にしない)
    (out / "members.json").write_text(
        json.dumps(dict(source=str(step),
                        scale=SCALE,
                        members=members),
                   ensure_ascii=False,
                   indent=1),
        encoding="utf-8")
    print(f"{len(members)} 部材 → {out}")


if __name__ == "__main__":
    main()

再 - pywinauto for python で copilot デスクトップアプリへ入力後、生成回答を取得

pywinauto for python で copilot デスクトップアプリへ入力後、生成回答を取得 - end0tknr's kipple - web写経開発

先日、上記entryを記載しましたが、動作しないpcを発見。 どうやら、mscopilot.exe より新しい? m365copilot.exe が動作していることが 原因らしい。

そこで、m365copilot.exe 対応版として以下のように実装

# -*- coding: utf-8 -*-

import os
import sys
import time
import glob
import subprocess
import pyperclip
import traceback
from pywinauto import Desktop
from pywinauto.keyboard import send_keys

COPILOT_EXE_DIRS = [ r"C:\Program Files\WindowsApps"]
COPILOT_EXES = [ "m365copilot.exe"]

app_base_dir = os.path.dirname(os.path.abspath(__file__))

def main():
    # copilot window取得。なければ、copilot起動
    copilot_win = get_copilot_window()

    # 「新しいチャット」に切替え
    click_new_chat( copilot_win )
    copilot_win.set_focus()
    time.sleep( 1 )

    # 思考modeを切替え
    # set_mode(copilot_win, "Think Deeper")
    # copilot_win.set_focus()
    # time.sleep( 1 )

    # fileを添付
    attach_file_path = app_base_dir + "/question.txt"
    attach_file_path = os.path.abspath( attach_file_path )
    upload_attach_file( copilot_win, attach_file_path )
    copilot_win.set_focus()
    time.sleep( 5 )

    #input_txt = """東京都の人口は?"""
    input_txt = """添付ファイル内に記載された質問に答えてください"""
    print("INPUT TXT:", input_txt )
    input_txt_and_wait( copilot_win, input_txt )

    response = read_assistant_text( copilot_win )
    print("RESPONSE:", response )


def input_txt_and_wait( win, text ):
    edit = find_input_box( win )

    # 応答完了判定の為、送信前のcopyボタン数を記録
    baseline_copy = len( count_copy_buttons(win) )

    edit.click_input()
    
    # クリップボード経由でテキスト貼付け
    pyperclip.copy( text )
    time.sleep(0.5)
    send_keys("^v")
    time.sleep(0.5)
    send_keys("{ENTER}")

    return wait_for_response(win, baseline_copy)

        
def find_copilot_exe_path():
    for base in COPILOT_EXE_DIRS:
        for exe_name in COPILOT_EXES:
            path_hits = glob.glob( os.path.join(base,"**",exe_name),
                                   recursive=True )
        if path_hits:
            return path_hits[0]
    return None


def copilot_window_exists():
    """Copilotアプリのwindowが存在すれば True。"""
    try:
        spec = Desktop(backend="uia").window(
            title="Microsoft 365 Copilot",
            class_name="Microsoft 365 Copilot Host"
        )
        return spec.exists()
    except Exception:
        return False


def get_copilot_window():
    if not copilot_window_exists():
        launch_copilot()
        
    desk = Desktop(backend="uia")
    spec = desk.window(title="Microsoft 365 Copilot",
                       class_name="Microsoft 365 Copilot Host" )
    timeout = 15
    spec.wait("exists visible", timeout=timeout)
    win = spec.wrapper_object()
    win.set_focus()
    time.sleep( 2 )    # ChromiumのAccessibility(a11y)ツリー構築待ち
    #send_keys("{ESC}")  # 開いたままのメニュー/ポップオーバーを閉じる
    #time.sleep( 2 )
    return win


def launch_copilot():
    try:
        exe_path = find_copilot_exe_path()
        if exe_path:
            subprocess.Popen([exe_path])
        else:
            # win専用 python関数で、protocol/app起動
            os.startfile("ms-copilot:")

        time.sleep( 5 )
            
        timeout=40
        deadline = time.time() + timeout
        while time.time() < deadline:
            time.sleep(2.0)
            if copilot_window_exists():
                return True
            
    except Exception as e:
        print( e )
        print( traceback.format_exc() )
    return False


def find_input_box( win ):
    try:
        timeout=10
        deadline = time.time() + timeout
        while time.time() < deadline:
            for d in win.descendants():
                # print( d.element_info.automation_id,
                #        d.element_info.control_type )
                if d.element_info.automation_id == \
                   "m365-chat-editor-target-element" and \
                   d.element_info.control_type == "Edit":
                    return d
            time.sleep( 1 )
    except Exception as e:
        print( e )
        print( traceback.format_exc() )


def click_new_chat(win, timeout=10):
    """左ペインの「新しいチャット」をクリック """
    deadline = time.time() + timeout
    while time.time() < deadline:
        for d in win.descendants():
            # print( d.element_info.control_type, d.window_text() )
            
            try:
                if (d.element_info.control_type == "Hyperlink"
                        and d.window_text() == "新しいチャット"):
                    d.click_input()
                    time.sleep( 2 )  # 新規チャット画面の描画とa11y再構築を待つ
                    return True
            except Exception:
                continue
        time.sleep( 1 )
    return False


def set_mode(win, mode_name, timeout=10):
    """応答モードを切り替える。mode_name はメニュー項目名の先頭一致
    (例: 'Think Deeper', 'Smart')。"""
    deadline = time.time() + timeout
    # 1) 応答モードボタンを押してメニューを開く
    while time.time() < deadline:
        btn = None
        for d in win.descendants():
            try:
                if (d.element_info.control_type == "Button"
                        and d.window_text().startswith("応答モード")):
                    btn = d
                    break
            except Exception:
                continue
        if btn is not None:
            btn.click_input()
            time.sleep(1.0)
            break
        time.sleep(0.5)
    else:
        raise RuntimeError("応答モードボタンが見つかりません")

    # 2) 目的のモードの MenuItem をクリック
    deadline = time.time() + timeout
    while time.time() < deadline:
        for d in win.descendants():
            try:
                if (d.element_info.control_type == "MenuItem"
                        and d.window_text().startswith(mode_name)):
                    d.click_input()
                    print(f"応答モードを「{mode_name}」に切替え")
                    time.sleep(0.8)
                    return True
            except Exception:
                continue
        time.sleep(0.5)
    raise RuntimeError(f"モード「{mode_name}」のメニュー項目が見つかりません")


def count_copy_buttons(win):
    btns = []
    for d in win.descendants():
        # print( d.element_info.control_type,  d.window_text() )
        
        if d.element_info.control_type == "Button" and \
           "コピー" in d.window_text():
            btns.append(d)
    return btns


def read_assistant_text( win ):
    
    groups = []
    for d in win.descendants():
        if d.element_info.control_type == "Group" and \
           "Copilot said" in d.window_text():
            groups.append( d )
    if len(groups) == 0:
        return None
    
    parts = []
    for t in groups[-1].descendants():
        #print( t.element_info.control_type, t.window_text() )
        if t.element_info.control_type in ["Text","ListItem"]:
            res_txt = t.window_text().replace("Copilot said", "").strip()
            parts.append( res_txt )
    return "\n".join(parts)


def wait_for_response(win, baseline_copy_count, timeout=90):
    deadline = time.time() + timeout
    last_text = None
    stable = 0
    while time.time() < deadline:
        n = len( count_copy_buttons(win))
        text = read_assistant_text(win)
        
        # 応答のcopyボタン表示で、回答完了と判断
        if n > baseline_copy_count and text:
            if text == last_text:
                stable += 1
                if stable >= 2:  # 約2サイクル安定したら確定
                    return True
            else:
                stable = 0
        last_text = text
        time.sleep(1.0)
    return False


def find_copilot_ui_element( win, lambda_func ):
    try:
        for d in win.descendants():
            # print( d.element_info.automation_id,"&",
            #        d.element_info.control_type,"&",
            #        d.window_text() )
            
            if lambda_func( d ):
                return d
    except Exception as e:
        print( e )
        print( traceback.format_exc() )
        

def upload_attach_file(win, path, timeout=10):

    add_btn = find_copilot_ui_element(
        win,
        lambda d: d.element_info.control_type =="Image" and \
               d.window_text() == "ソースの追加と管理")
    print( add_btn )
    add_btn.click_input()
    time.sleep( 1 )
    send_keys("{DOWN}")
    send_keys("{RIGHT}")
    send_keys("{ENTER}")
    
    # common dialogの file名欄にpathを貼付け
    pyperclip.copy( path )
    send_keys("^v")
    send_keys("{ENTER}")

    # 添付tipの出現待ち
    fname = os.path.basename( path )
    deadline = time.time() + timeout
    while time.time() < deadline:
        for d in win.descendants():
            if d.element_info.control_type == "Text" and \
               d.window_text() == fname:
                return True
        time.sleep( 1 )
    return False


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    main()

pywinauto for python で copilot デスクトップアプリへ入力後、生成回答を取得

# -*- coding: utf-8 -*-

import os
import sys
import time
import glob
import subprocess
import pyperclip
import traceback
from pywinauto import Desktop
from pywinauto.keyboard import send_keys

COPILOT_EXE_DIRS = [ r"C:\Program Files (x86)\Microsoft\Copilot",
                     r"C:\Program Files\Microsoft\Copilot" ]

app_base_dir = os.path.dirname(os.path.abspath(__file__))

def main():
    # copilot window取得。なければ、copilot起動
    copilot_win = get_copilot_window()

    # 「新しいチャット」に切替え
    click_new_chat( copilot_win )
    copilot_win.set_focus()
    time.sleep( 1 )

    # 思考modeを切替え
    # set_mode(copilot_win, "Think Deeper")
    # copilot_win.set_focus()
    # time.sleep( 1 )

    # fileを添付
    # attach_file_path = app_base_dir + "/question.txt"
    # attach_file_path = os.path.abspath( attach_file_path )
    # attach_file( copilot_win, attach_file_path )
    # copilot_win.set_focus()
    # time.sleep( 1 )

    input_txt = """東京都の人口は?
"""
    input_txt_and_wait( copilot_win, input_txt )

    response = get_response( copilot_win )
    print( response )


def input_txt_and_wait( win, text ):
    edit = find_input_box( win )

    # 応答完了判定の為、送信前のcopyボタン数を記録
    baseline_copy = len( count_copy_buttons(win) )

    edit.click_input()
    
    # クリップボード経由でテキスト貼付け
    pyperclip.copy( text )
    time.sleep(0.5)
    send_keys("^v")
    time.sleep(0.5)
    send_keys("{ENTER}")

    return wait_for_response(win, baseline_copy)

        
def find_copilot_exe_path():
    for base in COPILOT_EXE_DIRS:
        path_hits = glob.glob(os.path.join(base, "**", "mscopilot.exe"), recursive=True)
        if path_hits:
            return path_hits[0]
    return None


def copilot_window_exists():
    """Copilotアプリのwindowが存在すれば True。"""
    try:
        spec = Desktop(backend="uia").window( title="Copilot",
                                              class_name="Chrome_WidgetWin_1")
        return spec.exists()
    except Exception:
        return False


def get_copilot_window():
    if not copilot_window_exists():
        launch_copilot()
        
    desk = Desktop(backend="uia")
    spec = desk.window(title="Copilot", class_name="Chrome_WidgetWin_1")

    timeout = 15
    spec.wait("exists visible", timeout=timeout)
    win = spec.wrapper_object()
    win.set_focus()
    time.sleep( 2 )    # ChromiumのAccessibility(a11y)ツリー構築待ち
    #send_keys("{ESC}")  # 開いたままのメニュー/ポップオーバーを閉じる
    #time.sleep( 2 )
    return win


def launch_copilot():
    try:
        exe_path = find_copilot_exe_path()
        if exe_path:
            subprocess.Popen([exe_path])
        else:
            # win専用 python関数で、protocol/app起動
            os.startfile("ms-copilot:")

        timeout=40
        deadline = time.time() + timeout
        while time.time() < deadline:
            time.sleep(2.0)
            if copilot_window_exists():
                return True
            
    except Exception as e:
        print( e )
        print( traceback.format_exc() )
    return False


def find_input_box( win ):
    try:
        timeout=10
        deadline = time.time() + timeout
        while time.time() < deadline:
            for d in win.descendants():
                if d.element_info.automation_id == "userInput" and \
                   d.element_info.control_type == "Edit":
                    return d
            time.sleep( 1 )
    except Exception as e:
        print( e )
        print( traceback.format_exc() )


def click_new_chat(win, timeout=10):
    """左ペインの「新しいチャット」ボタンをクリックする。"""
    deadline = time.time() + timeout
    while time.time() < deadline:
        for d in win.descendants():
            try:
                if (d.element_info.control_type == "Button"
                        and d.window_text() == "新しいチャット"):
                    d.click_input()
                    print("「新しいチャット」をクリックしました。")
                    time.sleep(1.2)  # 新規チャット画面の描画とa11y再構築を待つ
                    return True
            except Exception:
                continue
        time.sleep(0.5)
    raise RuntimeError("「新しいチャット」ボタンが見つかりません")


def set_mode(win, mode_name, timeout=10):
    """応答モードを切り替える。mode_name はメニュー項目名の先頭一致
    (例: 'Think Deeper', 'Smart')。"""
    deadline = time.time() + timeout
    # 1) 応答モードボタンを押してメニューを開く
    while time.time() < deadline:
        btn = None
        for d in win.descendants():
            try:
                if (d.element_info.control_type == "Button"
                        and d.window_text().startswith("応答モード")):
                    btn = d
                    break
            except Exception:
                continue
        if btn is not None:
            btn.click_input()
            time.sleep(1.0)
            break
        time.sleep(0.5)
    else:
        raise RuntimeError("応答モードボタンが見つかりません")

    # 2) 目的のモードの MenuItem をクリック
    deadline = time.time() + timeout
    while time.time() < deadline:
        for d in win.descendants():
            try:
                if (d.element_info.control_type == "MenuItem"
                        and d.window_text().startswith(mode_name)):
                    d.click_input()
                    print(f"応答モードを「{mode_name}」に切り替えました。")
                    time.sleep(0.8)
                    return True
            except Exception:
                continue
        time.sleep(0.5)
    raise RuntimeError(f"モード「{mode_name}」のメニュー項目が見つかりません")


def count_copy_buttons(win):
    btns = []
    for d in win.descendants():
        if d.element_info.control_type == "Button" and \
           d.window_text() == "メッセージをコピー":
            btns.append(d)
    return btns


def read_assistant_text( win ):
    
    groups = []
    for d in win.descendants():
        if d.element_info.control_type == "Group" and \
           d.window_text() == "Copilot の発言":
            groups.append( d )

    if len(groups) == 0:
        return None
    
    parts = []
    for t in groups[-1].descendants():
        if t.element_info.control_type == "Text":
            parts.append(t.window_text())
            
    return "\n".join(parts)


def wait_for_response(win, baseline_copy_count, timeout=90):
    deadline = time.time() + timeout
    last_text = None
    stable = 0
    while time.time() < deadline:
        n = len( count_copy_buttons(win))
        text = read_assistant_text(win)
        
        # 応答のcopyボタンが出ていれば、回答完了
        if n >= baseline_copy_count + 2 and text:
            if text == last_text:
                stable += 1
                if stable >= 2:  # 約2サイクル安定したら確定
                    return True
            else:
                stable = 0
        last_text = text
        time.sleep(1.0)
    return False


def get_response( win ):
    """最新のCopilot応答本文を取得 """
    txt = read_assistant_text(win)
    if txt:
        # 先頭に付くグループ名ラベルを除去
        if txt.startswith("Copilot の発言"):
            txt = txt[len("Copilot の発言"):].lstrip("\n")
            
    return txt


def find_attach_file_button( win ):
    def find_ui_element( lambda_func ):
        try:
            for d in win.descendants():
                if lambda_func( d ):
                    return d
        except Exception as e:
            print( e )
            print( traceback.format_exc() )
        return None

    # menuを開く
    add_btn = None
    for _ in range(4):
        btn = find_ui_element(lambda d: d.element_info.automation_id == "composer-create-button")
        if not btn:
            time.sleep( 1 )
            continue
        btn.click_input()
        
        for _ in range(8):
            time.sleep( 1 )
            add_btn = find_ui_element(
                lambda d: d.element_info.control_type == "Button" \
                and d.window_text() == "画像またはファイルを追加" )
            
            if add_btn != None:
                break
        if add_btn:
            time.sleep( 1 )
            return add_btn
        

def attach_file(win, path, timeout=10):
    # file追加buttonをclick → common dialogにfocus移動
    add_button = find_attach_file_button( win )
    add_button.click_input()
    time.sleep( 2 )

    # common dialogの file名欄にpathを貼付け
    pyperclip.copy( path )
    time.sleep( 1 )
    send_keys("^v")
    time.sleep( 1 )
    send_keys("{ENTER}")

    # 添付tipの出現待ち
    fname = os.path.basename( path )
    deadline = time.time() + timeout
    while time.time() < deadline:
        for d in win.descendants():
            if d.element_info.control_type == "Text" and \
               d.window_text() == fname:
                return True
        time.sleep( 1 )
    return False


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    main()

paddleocr for python による ai ocr

GitHub - PaddlePaddle/PaddleOCR: Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between images/PDFs and LLMs. Supports 100+ languages. · GitHub

MinerU、chandra に続く、ai ocr。

使いやすさや精度は、paddleocrが最も良い気がします

目次

pip install

OCRライブラリ本体(paddleocr)と、推論エンジン(paddlepaddle-gpu)をinstall

CMD> python3.12\python.exe -m pip install paddleocr
CMD> python3.12\python.exe -m pip install paddlepaddle-gpu==3.3.1 -i https://www.paddlepaddle.org.cn/packages/stable/cu118/
CMD> python3.12\python.exe -m pip install "paddlex[ocr]==3.7.2"

gpuの接続確認

import paddle
paddle.utils.run_check()               # "PaddlePaddle works well on N GPUs" と出ればOK
print(paddle.device.get_device())      # "gpu:0" のように表示される
print(paddle.is_compiled_with_cuda())  # True

↑こうかくと、↓こう表示

C:\Users\end0t\tmp\PADDLE_OCR>python3.12\python.exe chk_gpu.py
Running verify PaddlePaddle program ...
C:\Users\end0t\tmp\PADDLE_OCR\python3.12\Lib\site-packages\paddle\pir\math_op_patch.py:241:
UserWarning: Tensor do not have 'place' interface for pir graph mode, try not to use it.
None will be returned.

  warnings.warn(
I0829 15:04:05.538084 27788 pir_interpreter.cc:1529] New Executor is Running ...
WARNING: Logging before InitGoogleLogging() is written to STDERR
W0829 15:04:05.538084 27788 gpu_resources.cc:116] Please NOTE: device: 0,
  GPU Compute Capability: 8.9, Driver API Version: 13.0, Runtime API Version: 11.8
I0829 15:04:05.768106 27788 pir_interpreter.cc:1552]
  pir interpreter is running by multi-thread mode ...
  
PaddlePaddle works well on 1 GPU.
PaddlePaddle is installed successfully! Let's start deep learning with PaddlePaddle now.
gpu:0  ★
True   ★

PaddleOCR - text抽出のみ

import sys
import time
from paddleocr import PaddleOCR

# Windowsコンソール(cp932)の文字化け対策:標準出力をUTF-8にする
sys.stdout.reconfigure(encoding="utf-8")

# device="gpu:0" でGPU使用(PaddleOCR 3.x系)
ocr = PaddleOCR(lang="japan", device="gpu:0")

img = "sample.png"   # ← 手元の画像パスに変更

t0 = time.time()
result = ocr.predict(img)      # 3.x は predict()
print(f"処理時間: {time.time()-t0:.2f}秒")

# 結果表示(3.x の戻り値形式)
for res in result:
    # テキストとスコアだけを見やすく表示
    for text, score in zip(res["rec_texts"], res["rec_scores"]):
        print(f"{score:.2f}  {text}")

    # 可視化画像は「フォルダ」を指定(複数画像が出力される)
    res.save_to_img("output")
    # 認識結果はJSON(UTF-8)で保存
    res.save_to_json("output")

PPStructureV3 - 文章・図・表の混在文書

from paddleocr import PPStructureV3

pipeline = PPStructureV3(
    lang="japan",
    device="gpu:0",
    use_formula_recognition=False,       # 数式が無い文書なら切る
    use_table_recognition=True,          # 表は使う
    use_doc_orientation_classify=False,  # 傾き分類(不要なら切って高速化)
    use_doc_unwarping=False,             # 歪み補正(不要なら切って高速化)
)

results = pipeline.predict("sample.png")
for res in results:
    res.save_to_markdown("output_structure")  # 表はHTML、図は画像で埋込
    res.save_to_img("output_structure")       # レイアウト枠の可視化
    res.save_to_json("output_structure")      # 全構造データ

PPStructureV3が内部で使うmodel

predict()の初回実行時に以下が自動的にダウンロード

役割 モデル
レイアウト検出 PP-DocLayout_plus-L
テキスト検出/認識 PP-OCRv5_server_det / _rec
表の有線/無線判定 PP-LCNet_x1_0_table_cls
表構造復元 SLANeXt_wired / SLANet_plus
表セル検出 RT-DETR-L_wired/wireless_table_cell_det
数式認識 PP-FormulaNet_plus-L

上記により出力される結果file群

ファイル 内容
sample.md 本命の成果物。表は html table、図はimgs/へ切り出してで埋込
imgs/ 図・表の切り出し画像
sample_layout_det_res.png 領域分割の可視化(先ほど送った画像)
sample_layout_order_res.png 読み取り順序(reading order)
sample_table_cell_img.png 表セル検出の可視化
sample_res.json 全領域の種別・座標・テキスト・表HTML

表のhtmlのみ出力する場合

for res in results:
    for block in res["parsing_res_list"]:
        if block["block_label"] == "table":
            print(block["block_content"])   # 表のHTML

markdownのみ出力する場合

from paddleocr import PPStructureV3
from pathlib import Path
import glob

def main():
    # https://www.paddleocr.ai/main/en/version3.x/pipeline_usage/PP-StructureV3.html
    pipeline = PPStructureV3(
        lang  ="japan",
        device="gpu:0",
        use_formula_recognition     =False,     # 数式
        use_table_recognition       =True,      # 表
        use_doc_orientation_classify=False,     # 傾き分類
        use_doc_unwarping           =False,     # 歪み補正
        # 解析結果に含まれるblock内容を、markdownなどへ出力しやすい様、整形
        format_block_content=True,

        # markdownから除外する要素
        markdown_ignore_labels=[
            "image","figure","header_image","footer_image"],
    )

    Path("output_md").mkdir(exist_ok=True)

    for i, png_path in enumerate(glob.glob("input_trim_png/*.png")):

        basename = Path(png_path).stem
        out_path = Path("output_md") / f"{basename}.md"
        
        print(i, png_path, out_path)
        
        results = pipeline.predict(png_path) # layout解析実行
        markdown_list = []

        for res in results:
            # PPStructureV3が生成したMarkdownを取得
            md_info = res.markdown
            markdown_text = md_info.get("markdown_texts", "")

            markdown_list.append(markdown_text)

        out_path.write_text( "\n\n".join(markdown_list),
                             encoding="utf-8" )


if __name__ == "__main__":
    main()

PaddleOCRVL - 文章・図・表の混在文書 (その2)

PaddleOCRVLの方が高精度版らしいが、私はPPStructureV3の方が高精度に感じました

import sys
import time
from paddleocr import PaddleOCRVL

# Windowsコンソール(cp932)の文字化け対策
sys.stdout.reconfigure(encoding="utf-8")

# VLM(Vision-Languageモデル)ベースの文書パーサ
#   レイアウト検出 + PaddleOCR-VL による認識で、図表・数式込みのMarkdownを生成
pipeline = PaddleOCRVL()

img = "sample.png"

t0 = time.time()
results = pipeline.predict(img)
print(f"処理時間: {time.time()-t0:.2f}秒")

for res in results:
    res.save_to_markdown("output_vl")  # 図表・数式込みのMarkdown
    res.save_to_json("output_vl")      # 構造データ

windows os付属のocrを winsdk for pythonから利用

  • windows os付属のocrなので、お手軽。しかも処理が速い
  • yahooトップを画面キャプチャし、テスト
  • 画像サイズを拡大すると、精度UPしそう

pip install

CMD> pip install winsdk

python script

import sys
import os
import asyncio

from winsdk.windows.media.ocr        import OcrEngine
from winsdk.windows.globalization    import Language
from winsdk.windows.storage          import StorageFile
from winsdk.windows.graphics.imaging import BitmapDecoder


def main():
    img_path = sys.argv[1]
    asyncio.run( ocr_image( img_path ) )


async def ocr_image( image_path ):

    # Windowsのfile obj取得
    image_file = await StorageFile.get_file_from_path_async(
        os.path.abspath( image_path ) )

    # 画像ファイルを開く
    stream = await image_file.open_async(0)

    # 画像をSoftwareBitmapへ変換
    decoder = await BitmapDecoder.create_async(stream)
    bitmap = await decoder.get_software_bitmap_async()

    # 日本語ocr実行
    engine = OcrEngine.try_create_from_language( Language("ja-JP") )
    result = await engine.recognize_async(bitmap)

    print("=== OCR結果 ===")
    print(result.text)

    print("=== 行・単語・座標 ===")

    for line in result.lines:
        print(f"\nLINE: {line.text}")

        for word in line.words:
            rect = word.bounding_rect
            print(
                f"WORD: {word.text} "
                f"x={rect.x:.1f} "
                f"y={rect.y:.1f} "
                f"w={rect.width:.1f} "
                f"h={rect.height:.1f}"
            )

    stream.close()
    

if __name__ == "__main__":
    main()

実行結果

C:\Users\end0t\tmp\WIN_OCR>..\..\python3.12\python.exe win_ocr_2.py yahoo_2.png
=== OCR結果 ===
0 も し 明 日 か ら 働 か な く て い い な ら 、 何 す る ? 0 プ レ ミ ア ム オ ー ク シ ョ ン シ ョ ッ ピ ン ク ウ エ プ AI モ - ド 画 像 0 ( JAPI 動 画 知 恵 袋 地 図 リ ア ル タ イ 北 陸 で 大 雨 気 象 情 報 や 交 通 影 響 な ど 》 い つ も な ん だ か 変 な ポ - ス を し て い る 、 ビ ッ ク ア ッ プ 直 ー ト ラ ベ ル お ト ク な セ - ル 開 催 中 ・ 、 オ - ク シ ョ ン 週 末 限 定 ク - ホ ン 配 布 ッ ピ ン グ 経 済 工 ン タ メ ス ポ - ツ 国 内 国 際 8 / 29 ( 土 ) 14 : 10 更 新 北 陸 な ど 警 報 級 大 雨 恐 れ 災 害 警 戒 ・ 円 が 下 落 介 人 効 果 4 週 問 で 陰 り 海 で 不 明 の 中 高 生 か 2 人 死 亡 確 認 ・ 長 女 が 重 体 傷 害 の 疑 い で 両 親 逮 捕 「 皇 居 ラ ン 」 に 舌 情 区 の 担 当 者 は ・ 大 河 ド ラ マ 巡 り 2 市 が NHK に 文 書 主 要 66 747 68 855 D2311 255 IT 科 ワ イ ) 8 / 29 は 宮 崎 日
=== 行・単語・座標 ===

LINE: 0 も し 明 日 か ら 働 か な く て い い な ら 、 何 す る ?
WORD: 0 x=15.0 y=7.0 w=21.0 h=19.0
WORD: も x=46.0 y=6.0 w=16.0 h=15.0
WORD: し x=67.0 y=7.0 w=15.0 h=14.0
WORD: 明 x=84.0 y=6.0 w=16.0 h=16.0
WORD: 日 x=104.0 y=6.0 w=15.0 h=16.0
WORD: か x=122.0 y=6.0 w=18.0 h=15.0
WORD: ら x=143.0 y=6.0 w=15.0 h=15.0
WORD: 働 x=160.0 y=6.0 w=18.0 h=16.0
WORD: か x=180.0 y=6.0 w=18.0 h=15.0
WORD: な x=199.0 y=6.0 w=18.0 h=16.0
WORD: く x=221.0 y=6.0 w=12.0 h=16.0
WORD: て x=238.0 y=8.0 w=17.0 h=13.0
WORD: い x=257.0 y=8.0 w=17.0 h=13.0
WORD: い x=277.0 y=8.0 w=17.0 h=13.0
WORD: な x=295.0 y=6.0 w=18.0 h=16.0
WORD: ら x=316.0 y=6.0 w=15.0 h=15.0
WORD: 、 x=334.0 y=17.0 w=5.0 h=5.0
WORD: 何 x=352.0 y=5.0 w=19.0 h=17.0
WORD: す x=373.0 y=6.0 w=17.0 h=16.0
WORD: る x=392.0 y=7.0 w=16.0 h=15.0
WORD: ? x=415.0 y=7.0 w=9.0 h=14.0

LINE: 0
WORD: 0 x=165.0 y=61.0 w=55.0 h=55.0

LINE: プ レ ミ ア ム
WORD: プ x=141.0 y=123.0 w=20.0 h=20.0
WORD: レ x=164.0 y=126.0 w=17.0 h=17.0
WORD: ミ x=184.0 y=126.0 w=17.0 h=17.0
WORD: ア x=204.0 y=126.0 w=20.0 h=17.0
WORD: ム x=225.0 y=126.0 w=19.0 h=16.0

LINE: オ ー ク シ ョ ン シ ョ ッ ピ ン ク
WORD: オ x=290.0 y=125.0 w=20.0 h=18.0
WORD: ー x=312.0 y=134.0 w=18.0 h=2.0
WORD: ク x=332.0 y=126.0 w=19.0 h=17.0
WORD: シ x=354.0 y=126.0 w=19.0 h=17.0
WORD: ョ x=376.0 y=130.0 w=14.0 h=12.0
WORD: ン x=397.0 y=126.0 w=17.0 h=17.0
WORD: シ x=451.0 y=126.0 w=18.0 h=17.0
WORD: ョ x=473.0 y=130.0 w=14.0 h=12.0
WORD: ッ x=494.0 y=129.0 w=15.0 h=14.0
WORD: ピ x=515.0 y=123.0 w=17.0 h=20.0
WORD: ン x=535.0 y=126.0 w=18.0 h=17.0
WORD: ク x=554.0 y=125.0 w=21.0 h=18.0

LINE: ウ エ プ AI モ - ド 画 像
WORD: ウ x=392.0 y=188.0 w=20.0 h=20.0
WORD: エ x=415.0 y=193.0 w=19.0 h=15.0
WORD: プ x=436.0 y=187.0 w=23.0 h=21.0
WORD: AI x=480.0 y=190.0 w=24.0 h=17.0
WORD: モ x=506.0 y=190.0 w=21.0 h=17.0
WORD: - x=529.0 y=198.0 w=19.0 h=2.0
WORD: ド x=556.0 y=188.0 w=15.0 h=20.0
WORD: 画 x=594.0 y=189.0 w=22.0 h=19.0
WORD: 像 x=617.0 y=188.0 w=22.0 h=20.0

LINE: 0 (
WORD: 0 x=888.0 y=71.0 w=65.0 h=44.0
WORD: ( x=956.0 y=64.0 w=31.0 h=47.0

LINE: JAPI
WORD: JAPI x=897.0 y=120.0 w=90.0 h=35.0

LINE: 動 画 知 恵 袋 地 図 リ ア ル タ イ
WORD: 動 x=661.0 y=188.0 w=21.0 h=20.0
WORD: 画 x=684.0 y=189.0 w=21.0 h=19.0
WORD: 知 x=727.0 y=188.0 w=21.0 h=21.0
WORD: 恵 x=750.0 y=187.0 w=22.0 h=21.0
WORD: 袋 x=773.0 y=188.0 w=22.0 h=20.0
WORD: 地 x=816.0 y=188.0 w=22.0 h=20.0
WORD: 図 x=840.0 y=189.0 w=21.0 h=19.0
WORD: リ x=886.0 y=189.0 w=16.0 h=18.0
WORD: ア x=907.0 y=190.0 w=21.0 h=18.0
WORD: ル x=928.0 y=189.0 w=23.0 h=19.0
WORD: タ x=952.0 y=189.0 w=20.0 h=19.0
WORD: イ x=975.0 y=194.0 w=12.0 h=14.0

<略>

Document AIの chandra for python & docker で png画像を markdown化

先日のentry群に続き、Datalab社の chandraのお試し。

処理が重いことが示しているのでしょうか、 これまでに試した、yomitoku、mineruより精度がグッと向上した気がします

環境 - windows & wsl & docker

chandraの modelである datalab-to/chandra-ocr-2 は、huggingface(hf) または、vllm で動作しますが、hf でのocr処理が、余りに遅かった為、 wslや dockerも用意。

尚、wsl内にあるosは、OracleLinux_9_5で、このwslからeGPUである geforce rtc4090へ接続

C:\Users\end0t\tmp\CHANDRA>python3.12\Scripts\chandra.exe --help
Usage: chandra [OPTIONS] INPUT_PATH OUTPUT_PATH

Options:
  --method [hf|vllm]              Inference method: 'hf' for local model,
                                  'vllm' for vLLM server.
  --page-range TEXT               Page range for PDFs (e.g., '1-5,7,9-12').
                                  Only applicable to PDF files.
  --max-output-tokens INTEGER     Maximum number of output tokens per page.
  --max-workers INTEGER           Maximum number of parallel workers for vLLM
                                  inference.
  --max-retries INTEGER           Maximum number of retries for vLLM
                                  inference.
  --include-images / --no-images  Include images in output.
  --include-headers-footers / --no-headers-footers
                                  Include page headers and footers in output.
  --save-html / --no-html         Save HTML output files.
  --batch-size INTEGER            Number of pages to process in a batch.
  --paginate_output
  --help                          Show this message and exit.
C:\Users\end0t\tmp\CHANDRA>wsl --list
Linux 用 Windows サブシステム ディストリビューション:
OracleLinux_9_5 (既定値)

C:\Users\end0t\tmp\CHANDRA>wsl

[end0tknr@a64 CHANDRA]$ cat /etc/redhat-release
Red Hat Enterprise Linux release 9.5 (Plow)

install docker to wsl

docker for windowsも実は、wslに依存しているようですので、 wslへ インストール

sudo dnf -y install dnf-plugins-core
sudo dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo
sudo dnf -y install docker-ce docker-ce-cli containerd.io
sudo systemctl enable --now docker

install NVIDIA Container Toolkit to wsl

curl -s -L https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo | sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo
sudo dnf -y install nvidia-container-toolkit
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker

install vllm to wsl docker

vLLM イメージのコンテナを一時的に起動し、その中で nvidia-smi だけを実行して、 コンテナからGPUが見えるか確認。

※この実行時に Docker イメージ vllm/vllm-openai:v0.17.0がダウンロードされますが、 「--rm」オプションがある為、終了後、削除されます

※ vllm/vllm-openai:v0.27.1 のように新しいdocker imageもありますが、 chandra側が vllm/vllm-openai:v0.17.0 を指定している為、これを利用

[end0tknr@a64 end0t]$ sudo docker run --rm --runtime=nvidia --gpus all --entrypoint nvidia-smi vllm/vllm-openai:v0.17.0

+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 580.102.01             Driver Version: 581.57         CUDA Version: 13.0     |
+-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  NVIDIA GeForce RTX 4090        On  |   00000000:22:00.0 Off |                  Off |
|  0%   47C    P8             28W /  450W |       0MiB /  24564MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+

+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
|  No running processes found                                                             |
+-----------------------------------------------------------------------------------------+
引数 説明
--rm container終了時にcontainerを自動削除
--runtime=nvidia NVIDIA Container Toolkitをruntimeに使用
--gpus all hostの全GPUをcontainerに開示。1枚なら --gpus device=0 も可
--entrypoint nvidia-smi 元々のvllm serveでなく nvidia-smi を起動に利用
vllm/vllm-openai:v0.17.0 使うイメージ名とタグ(バージョン)

vLLM サーバ起動

初回起動時、 datalab-to/chandra-ocr-2 が huggingfaceから ダウンロードされます

sudo docker run --runtime nvidia --gpus device=0 \
  -v ~/.cache/huggingface:/root/.cache/huggingface \
  -p 8000:8000 --ipc=host \
  vllm/vllm-openai:v0.17.0 \
  --model datalab-to/chandra-ocr-2 \
  --no-enforce-eager \
  --max-num-seqs 16 \
  --dtype bfloat16 \
  --max-model-len 18000 \
  --max_num_batched_tokens 18000 \
  --gpu-memory-utilization .85 \
  --served-model-name chandra
引数 説明
--gpus device=0 nvidia-smiで表示された No.0のRTX4090をコンテナに割当て
-v ~/.cache/huggingface:/root/.cache/huggingface volume mount。host(WSL)の HuggingFace cacheを containerの /root/.cache/huggingface に共有
-p 8000:8000 port公開。左=ホスト側、右=コンテナ側
--ipc=host containerがhostのIPC空間(共有mem)使用。docker既定(64MB)ではpytorchに不足する為
--model datalab-to/chandra-ocr-2 Chandraのocr model本体。HuggingFaceの repo id
--no-enforce-eager CUDA graph / torch.compile 有効化。推論を高速化
--max-num-seqs 16 並列度の上限
--dtype bfloat16 modelの計算精度
--max-model-len 18000 1 reqで扱える最大token長
--max_num_batched_tokens 18000 1stepで処理するtokenの上限。max-model-lenと同値
--gpu-memory-utilization .85 GPU memの 85% をvLLMが使用。重み+KV cache用
--served-model-name chandra API公開するmodel名。VLLM_MODEL_NAME=chandraと一致

pip install chandra-ocr[hf]

python3.12\python.exe -m pip install chandra-ocr[hf]

python3.12\python.exe -m pip uninstall -y torch torchvision
python3.12\python.exe -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124

python3.12\python.exe -c "import torch; print(torch.cuda.is_available(), torch.version.cuda, torch.cuda.get_device_name(0))"

config chandra

vi C:\Users\end0t\tmp\CHANDRA\python3.12\Lib\site-packages\chandra\settings.py

172.18.129.236とは、wsl側のip

from dotenv import find_dotenv
from pydantic_settings import BaseSettings
import os


class Settings(BaseSettings):
    # Paths
    BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    IMAGE_DPI: int = 192
    MIN_PDF_IMAGE_DIM: int = 1024
    MIN_IMAGE_DIM: int = 1536
    MODEL_CHECKPOINT: str = "datalab-to/chandra-ocr-2"
    TORCH_DEVICE: str | None = None
    MAX_OUTPUT_TOKENS: int = 12384
    TORCH_ATTN: str | None = None
    BBOX_SCALE: int = 1000

    # vLLM server settings
    VLLM_API_KEY: str = "EMPTY"
    VLLM_API_BASE: str = "http://172.18.129.236:8000/v1"
    #VLLM_API_BASE: str = "http://localhost:8000/v1"
    VLLM_MODEL_NAME: str = "chandra"
    VLLM_GPUS: str = "0"
    MAX_VLLM_RETRIES: int = 6

    class Config:
        env_file = find_dotenv("local.env")
        extra = "ignore"


settings = Settings()

chandra実行

C:\Users\end0t\tmp\CHANDRA>python3.12\Scripts\chandra.exe ./input ./output --method vllm --include-images --no-html
Chandra CLI - Starting OCR processing
Input: input
Output: output
Method: vllm

Loading model with method 'vllm'...
Model loaded successfully.

Found 1 file(s) to process.

[1/1] Processing: 26A001-02-000_240.png
  Loaded 1 page(s)
  Processing pages 1-1...
  Saved: output\26A001-02-000_240\26A001-02-000_240.md (1 page(s))
  Completed: 26A001-02-000_240.png

Processing complete. Results saved to: output

RAG-Anything + python for win + ollama + 日本語

LightRAG を 開発した Data Intelligence Lab @ HKU による マルチモーダルRAG。

LightRAG の入力がテキストのみでしたが、 RAG-Anythingは、MinerU により、様々なデータを text化し、入力に利用。

LightRAGを内包しており、インデックス作成後、 LightRAGのweb uiを用い、検索できますが、 MinerUによるテキスト化がいまいちで、 また、インデックス化処理が、よくフリーズしましたので、 今後は、LightRAGを使用すると思います。

Document AIの MinerU for python で tiff画像を markdown化

Document AI yomitoku for python で png画像を html化 - end0tknr's kipple - web写経開発

以前、上記entryにある yomitoku を試しましたが、 似たライブラリである opendatalab/MinerU を見つけたので、お試し。

GitHub - opendatalab/MinerU: Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows. · GitHub

MinerU の README.md を読むと、MinerUの 多機能さに魅力を感じますが、 yomitokuの markdown化ファイルの方が、文字をより、抽出し、まとまっていましたので、 今後は、yomitokuを利用すると思います。

特徴

  • pdf, 画像, office(docx, pptx, xlsx ※1) を入力データとして対応
  • ヘッダー、フッター、脚注、ページ番号を削除
  • 画像、画像の説明、表、数式、脚注を抽出
  • スキャンされたpdfも ocr可能(109言語)

※1 別途、libreoffice要

install

CMD> python3.12\python.exe -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124

CMD> python3.12\python.exe -m pip install "mineru[all]"

使用方法 - mineru.exe --help

C:\Users\end0t\tmp\MINERU>python3.12\Scripts\mineru.exe --help
Usage: mineru [OPTIONS]

Options:
  -v, --version                   display the version and exit
  -p, --path PATH                 local filepath or directory. support pdf,
                                  image, docx, pptx, xlsx files  [required]
  -o, --output PATH               output local directory  [required]
  --api-url TEXT                  MinerU FastAPI base URL. If omitted, mineru
                                  starts a temporary local mineru-api service.
  -m, --method [auto|txt|ocr]
     the method for parsing pdf:
       auto: Automatically determine the method based on the file type.
       txt : Use text extraction method.
       ocr : Use OCR method for image-based PDFs.
     Without method specified, 'auto' will be used by default.
     Adapted only for the case where the backend is set to 'pipeline' and 'hybrid-*'.
  -b, --backend [pipeline|vlm-engine|hybrid-engine|vlm-http-client|hybrid-http-client]
     the backend for parsing pdf:
       pipeline       : More general.
       vlm-engine     : High accuracy via local computing power.
       vlm-http-client: High accuracy via remote computing power
                       (client suitable for openai-compatible servers).
       hybrid-engine  : Next-generation high accuracy solution
                        via local computing power.
       hybrid-http-client:
                        High accuracy but requires a little local computing power
                        (client suitable for openai-compatible servers).
       Without backend specified, hybrid-engine will be used by default.
  --effort [medium|high]
      Hybrid parsing effort:
        medium: Faster parsing for most documents,
                balancing accuracy and efficiency.
                Image/chart analysis is disabled.
        high:   Higher-accuracy parsing with image/chart analysis support,
                which may take longer.
      Without effort specified, medium will be used by default.
      Adapted only for the case where the backend is set to 'hybrid-*'.
  -l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
      Input the languages in the pdf (if known) to
      improve OCR accuracy. Without languages
      specified, 'ch' will be used by default.
      Specify document language (improves OCR
      accuracy, pipeline backend only).
  -u, --url TEXT                  When the backend is `<vlm/hybrid>-http-
                                  client`, you need to specify the server_url,
                                  for example:`http://127.0.0.1:30000`
  -s, --start INTEGER             The starting page for PDF parsing, beginning
                                  from 0.
  -e, --end INTEGER               The ending page for PDF parsing, beginning
                                  from 0.
  -f, --formula BOOLEAN           Enable formula parsing. Default is True.
  -t, --table BOOLEAN             Enable table parsing. Default is True.
  --image-analysis BOOLEAN        Enable image/chart analysis for VLM and
                                  hybrid backends. Hybrid medium effort
                                  automatically disables image/chart analysis.
                                  Default is True.
  --client-side-output-generation BOOLEAN
                                  Generate markdown and content lists locally
                                  from server-returned middle json, images,
                                  and original files.
  --help                          Show this message and exit.

実行

CMD> python3.12\Scripts\mineru.exe -p .\tiff -o .\out1 -b pipeline

または

CMD> python3.12\Scripts\mineru.exe -p .\tiff -o .\out3 -b hybrid-engine --effort high --image-analysis=True --formula=True --table=True

実行結果ファイル群

file note
~.md 見出し、本文、表(HTML/Markdown表)、数式(LaTeX)
~_content_list.json 文書をブロック単位で並べたもの
~_content_list_v2.json 〃
~_middle.json 解析の中間ファイル
~_model.json layout,ocr,表,数式など、各modelの推論結果
~_origin.pdf 元ファイル
~_layout.pdf レイアウト
images/ 抽出した画像の保存用dir