Upload 124 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- MM_tools/README.md +152 -0
- MM_tools/app/__init__.py +30 -0
- MM_tools/app/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/ledger/__init__.py +9 -0
- MM_tools/app/blueprints/ledger/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/ledger/__pycache__/routes.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/ledger/routes.py +346 -0
- MM_tools/app/blueprints/ledger/templates/ledger/index.html +379 -0
- MM_tools/app/blueprints/main/__init__.py +9 -0
- MM_tools/app/blueprints/main/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/main/__pycache__/routes.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/main/routes.py +10 -0
- MM_tools/app/blueprints/main/templates/main/index.html +216 -0
- MM_tools/app/blueprints/ocr/__init__.py +9 -0
- MM_tools/app/blueprints/ocr/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/ocr/__pycache__/routes.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/ocr/routes.py +200 -0
- MM_tools/app/blueprints/ocr/templates/ocr/index.html +586 -0
- MM_tools/app/blueprints/translation/__init__.py +9 -0
- MM_tools/app/blueprints/translation/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/translation/__pycache__/routes.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/translation/routes.py +98 -0
- MM_tools/app/blueprints/translation/templates/translation/index.html +358 -0
- MM_tools/app/blueprints/vlm/__init__.py +7 -0
- MM_tools/app/blueprints/vlm/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/vlm/__pycache__/routes.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/vlm/routes.py +151 -0
- MM_tools/app/blueprints/vlm/templates/vlm/index.html +313 -0
- MM_tools/app/blueprints/whisper/__init__.py +5 -0
- MM_tools/app/blueprints/whisper/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/whisper/__pycache__/routes.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/whisper/engine/__init__.py +0 -0
- MM_tools/app/blueprints/whisper/engine/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/whisper/engine/__pycache__/core.cpython-314.pyc +0 -0
- MM_tools/app/blueprints/whisper/engine/core.py +155 -0
- MM_tools/app/blueprints/whisper/engine/punctuation.py +110 -0
- MM_tools/app/blueprints/whisper/engine/translator.py +77 -0
- MM_tools/app/blueprints/whisper/routes.py +175 -0
- MM_tools/app/blueprints/whisper/templates/whisper/index.html +486 -0
- MM_tools/app/shared/__init__.py +1 -0
- MM_tools/app/shared/__pycache__/__init__.cpython-314.pyc +0 -0
- MM_tools/app/shared/__pycache__/models.cpython-314.pyc +0 -0
- MM_tools/app/shared/__pycache__/utils.cpython-314.pyc +0 -0
- MM_tools/app/shared/models.py +211 -0
- MM_tools/app/shared/utils.py +39 -0
- MM_tools/app/static/Flag_of_Japan_Customs.svg.png +3 -0
- MM_tools/app/static/HP1.png +3 -0
- MM_tools/app/static/exports/whisper_minutes.txt +1 -0
- MM_tools/app/static/exports/whisper_only_text.txt +1 -0
- MM_tools/app/static/exports/whisper_text_time.txt +1 -0
MM_tools/README.md
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI Tools
|
| 2 |
+
|
| 3 |
+
ローカル AI モデルを使った 4 つのツールを Flask + Blueprint で統合したアプリです。
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## 機能一覧
|
| 8 |
+
|
| 9 |
+
| # | ツール | URL | 概要 |
|
| 10 |
+
|---|--------|-----|------|
|
| 11 |
+
| ① | 多言語翻訳 | `/translation` | テキストを各国語へリアルタイム翻訳(LFM 2.5) |
|
| 12 |
+
| ② | OCR と翻訳 | `/ocr` | 画像から文字認識(GLM-OCR)→ 翻訳(LFM 2.5) |
|
| 13 |
+
| ③ | 表 OCR → Excel | `/ledger` | 帳簿・表の画像を解析して Excel に変換(Qwen3-VL) |
|
| 14 |
+
| ④ | VLM | `/vlm` | 画像+プロンプトで Qwen3-VL に自由に問い合わせ(ストリーミング) |
|
| 15 |
+
| ⑤ | 音声文字起こし | `/whisper` | 音声・動画ファイルを文字起こし(Whisper)+ 翻訳(LFM 2.5) |
|
| 16 |
+
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
## 起動方法
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
python run.py
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
ブラウザで `http://localhost:5000` を開く。
|
| 26 |
+
|
| 27 |
+
> ポート番号などは `config.py` で変更できます。
|
| 28 |
+
|
| 29 |
+
---
|
| 30 |
+
|
| 31 |
+
## 設定(config.py)
|
| 32 |
+
|
| 33 |
+
`run.py` と同じフォルダにある `config.py` を編集することで、各種設定を一括変更できます。
|
| 34 |
+
|
| 35 |
+
| 設定項目 | デフォルト | 説明 |
|
| 36 |
+
|----------|-----------|------|
|
| 37 |
+
| `FLASK_HOST` | `"0.0.0.0"` | `"127.0.0.1"` にするとローカルのみ接続可 |
|
| 38 |
+
| `FLASK_PORT` | `5000` | サーバーのポート番号 |
|
| 39 |
+
| `FLASK_DEBUG` | `False` | デバッグモード |
|
| 40 |
+
| `DEVICE` | `"cpu"` | モデルのデバイス。`"cuda"` / `"auto"` も指定可 |
|
| 41 |
+
| `WHISPER_COMPUTE_TYPE` | `"int8"` | GPU 時は `"float16"` を推奨 |
|
| 42 |
+
| `LFM_MODEL_PATH` | `models/lfm2.5_instruct` | LFM 2.5 モデルの場所 |
|
| 43 |
+
| `GLM_OCR_PATH` | `models/GLM_OCR` | GLM-OCR モデルの場所 |
|
| 44 |
+
| `QWEN_MODEL_PATH` | `models/Qwen3-VL-2B-Instruct` | Qwen3-VL モデルの場所 |
|
| 45 |
+
| `WHISPER_SMALL_ID` | `"small"` | Whisper Small のモデルID |
|
| 46 |
+
| `WHISPER_LARGE_ID` | `"deepdml/..."` | Whisper Large のモデルID |
|
| 47 |
+
| `UPLOAD_DIR` | `app/static/uploads` | 音声ファイルの一時保存先 |
|
| 48 |
+
| `EXPORT_DIR` | `app/static/exports` | 書き出しテキストの保存先 |
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
## 必要なモデル
|
| 53 |
+
|
| 54 |
+
`models/` フォルダ以下に配置してください(パスは `config.py` で変更可)。
|
| 55 |
+
|
| 56 |
+
```
|
| 57 |
+
models/
|
| 58 |
+
├── lfm2.5_instruct/ # LFM 2.5 ONNX(翻訳・① ② ④ 共通)
|
| 59 |
+
├── GLM_OCR/ # GLM-OCR(② OCR)
|
| 60 |
+
└── Qwen3-VL-2B-Instruct/ # Qwen3-VL(③ 表OCR)
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
> Whisper モデルは `faster-whisper` が初回起動時に自動ダウンロードします。
|
| 64 |
+
|
| 65 |
+
---
|
| 66 |
+
|
| 67 |
+
## 必要なパッケージ
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
pip install flask transformers pillow openpyxl faster-whisper
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
> venv はプロジェクトの 1 つ上の階層 `../venv/` に配置。
|
| 74 |
+
|
| 75 |
+
---
|
| 76 |
+
|
| 77 |
+
## フォルダ構成
|
| 78 |
+
|
| 79 |
+
```
|
| 80 |
+
AI-OCR/
|
| 81 |
+
│
|
| 82 |
+
├── run.py # 起動エントリポイント
|
| 83 |
+
├── config.py # 設定ファイル(モデルパス・ポート等)← ここを編集
|
| 84 |
+
├── README.md
|
| 85 |
+
│
|
| 86 |
+
├── models/ # AI モデル保存先(config.py で変更可)
|
| 87 |
+
│ ├── lfm2.5_instruct/
|
| 88 |
+
│ ├── GLM_OCR/
|
| 89 |
+
│ └── Qwen3-VL-2B-Instruct/
|
| 90 |
+
│
|
| 91 |
+
├── app/
|
| 92 |
+
│ ├── __init__.py # Flask アプリファクトリ
|
| 93 |
+
│ ├── templates/
|
| 94 |
+
│ │ └── base.html # 共通レイアウト(ナビ・背景・雪アニメーション)
|
| 95 |
+
│ ├── static/
|
| 96 |
+
│ │ ├── HP1.png # 背景画像
|
| 97 |
+
│ │ ├── Flag_of_Japan_Customs.svg.png # ナビロゴ
|
| 98 |
+
│ │ ├── uploads/ # 音声ファイル一時保存
|
| 99 |
+
│ │ └── exports/ # テキスト書き出し保存
|
| 100 |
+
│ ├── shared/
|
| 101 |
+
│ │ ├── models.py # 遅延ロード モデル管理(全 Blueprint 共用)
|
| 102 |
+
│ │ └── utils.py # SSE ヘルパー等
|
| 103 |
+
│ └── blueprints/
|
| 104 |
+
│ ├── main/ # / トップページ
|
| 105 |
+
│ ├── translation/ # /translation 多言語翻訳
|
| 106 |
+
│ ├── ocr/ # /ocr OCR と翻訳
|
| 107 |
+
│ ├── ledger/ # /ledger 表 OCR → Excel
|
| 108 |
+
│ ├── vlm/ # /vlm VLM(画像+プロンプト)
|
| 109 |
+
│ └── whisper/ # /whisper 音声文字起こし
|
| 110 |
+
│ └── engine/
|
| 111 |
+
│ └── core.py # 文字起こし + 翻訳コア
|
| 112 |
+
│
|
| 113 |
+
└── WhisperApp/ # 旧スタンドアロン版(参照用)
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
---
|
| 117 |
+
|
| 118 |
+
## 各ツールの詳細
|
| 119 |
+
|
| 120 |
+
### ① 多言語翻訳 `/translation`
|
| 121 |
+
- 左ボックスに原文を入力 → 右ボックスに翻訳結果をリアルタイム表示
|
| 122 |
+
- 原文言語は自動検出(Auto)または手動指定
|
| 123 |
+
- 翻訳先は日本語・英語ほか自由入力可
|
| 124 |
+
|
| 125 |
+
### ② OCR と翻訳 `/ocr`
|
| 126 |
+
- 画像をアップロード → GLM-OCR でテキスト抽出 → LFM 2.5 で翻訳
|
| 127 |
+
- 結果はリアルタイムにストリーミング表示
|
| 128 |
+
|
| 129 |
+
### ③ 表 OCR → Excel `/ledger`
|
| 130 |
+
- 帳簿・表形式の画像を Qwen3-VL-2B で解析
|
| 131 |
+
- JSON 構造を自動抽出 → openpyxl で Excel (.xlsx) に変換 → ダウンロード
|
| 132 |
+
|
| 133 |
+
### ④ VLM `/vlm`
|
| 134 |
+
- 画像をアップロードしてプロンプトで Qwen3-VL-2B に自由に問い合わせ
|
| 135 |
+
- プリセットボタン: 画像の概要・文字読み取り要約・HTML テーブル変換・フリー入力
|
| 136 |
+
- 結果はトークン単位でリアルタイムストリーミング表示
|
| 137 |
+
- HTML タグが含まれる場合はそのまま HTML レンダリング(テーブルなど)
|
| 138 |
+
|
| 139 |
+
### ⑤ 音声文字起こし `/whisper`
|
| 140 |
+
- .mp3 / .wav / .mp4 / .m4a / .ogg をドラッグ&ドロップでアップロード
|
| 141 |
+
- **Small**(高速・シアン枠)/ **Large-v3-turbo**(高精度・レッド枠)を選択
|
| 142 |
+
- 出力形式: タイムスタンプあり(`whisper_text_time.txt`)/ なし(`whisper_only_text.txt`)
|
| 143 |
+
- 翻訳オプション: LFM 2.5 で各セグメントを翻訳(「英語」「中国語」など言語名で指定)
|
| 144 |
+
- 処理中は右上にスピナー表示、結果はリアルタイムにストリーミング表示
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
## 注意事項
|
| 149 |
+
|
| 150 |
+
- モデルはすべて初回リクエスト時に遅延ロードされます(起動は即座に完了します)
|
| 151 |
+
- モデルのロード中は画面にステータスが表示されます
|
| 152 |
+
- CPU 動作が前提です。GPU を使う場合は `config.py` で `DEVICE = "cuda"`、`WHISPER_COMPUTE_TYPE = "float16"` に変更してください
|
MM_tools/app/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Flask アプリケーションファクトリ。"""
|
| 2 |
+
|
| 3 |
+
from flask import Flask
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def create_app() -> Flask:
|
| 7 |
+
"""
|
| 8 |
+
Flask アプリケーションを生成・設定して返す。
|
| 9 |
+
|
| 10 |
+
Returns:
|
| 11 |
+
Flask: 設定済みの Flask アプリインスタンス
|
| 12 |
+
"""
|
| 13 |
+
app = Flask(__name__, template_folder="templates")
|
| 14 |
+
|
| 15 |
+
# Blueprint の登録
|
| 16 |
+
from .blueprints.main import main_bp
|
| 17 |
+
from .blueprints.translation import translation_bp
|
| 18 |
+
from .blueprints.ocr import ocr_bp
|
| 19 |
+
from .blueprints.ledger import ledger_bp
|
| 20 |
+
from .blueprints.vlm import vlm_bp
|
| 21 |
+
from .blueprints.whisper import whisper_bp
|
| 22 |
+
|
| 23 |
+
app.register_blueprint(main_bp)
|
| 24 |
+
app.register_blueprint(translation_bp, url_prefix="/translation")
|
| 25 |
+
app.register_blueprint(ocr_bp, url_prefix="/ocr")
|
| 26 |
+
app.register_blueprint(ledger_bp, url_prefix="/ledger")
|
| 27 |
+
app.register_blueprint(vlm_bp, url_prefix="/vlm")
|
| 28 |
+
app.register_blueprint(whisper_bp, url_prefix="/whisper")
|
| 29 |
+
|
| 30 |
+
return app
|
MM_tools/app/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (1.51 kB). View file
|
|
|
MM_tools/app/blueprints/ledger/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint
|
| 2 |
+
|
| 3 |
+
ledger_bp = Blueprint(
|
| 4 |
+
"ledger",
|
| 5 |
+
__name__,
|
| 6 |
+
template_folder="templates",
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
from . import routes # noqa: E402, F401
|
MM_tools/app/blueprints/ledger/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (343 Bytes). View file
|
|
|
MM_tools/app/blueprints/ledger/__pycache__/routes.cpython-314.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
MM_tools/app/blueprints/ledger/routes.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ledger ブループリント ルーティング。
|
| 3 |
+
|
| 4 |
+
③ 表形式 OCR → Excel 出力ページ。
|
| 5 |
+
帳簿・表の画像を Qwen3-VL-2B で解析し、JSON → Excel に変換して提供する。
|
| 6 |
+
進捗は SSE (Server-Sent Events) でストリーミング送信する。
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import io
|
| 10 |
+
import re
|
| 11 |
+
import json
|
| 12 |
+
import threading
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
from flask import render_template, request, Response, stream_with_context, send_file
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
from . import ledger_bp
|
| 20 |
+
from app.shared.models import get_qwen_model
|
| 21 |
+
from app.shared.utils import sse_event
|
| 22 |
+
|
| 23 |
+
# 出力先ディレクトリ(プロジェクトルートの output/)
|
| 24 |
+
OUTPUT_DIR = Path(__file__).parent.parent.parent.parent / "output"
|
| 25 |
+
OUTPUT_DIR.mkdir(exist_ok=True)
|
| 26 |
+
|
| 27 |
+
# モデルは 1 スレッドのみ利用可能なため排他ロック
|
| 28 |
+
_model_lock = threading.Lock()
|
| 29 |
+
|
| 30 |
+
# 表データ抽出プロンプト
|
| 31 |
+
OCR_PROMPT = """この画像は帳簿・表をカメラで撮影したものです。
|
| 32 |
+
画像内の表形式データをすべて読み取り、以下のJSON形式のみで出力してください。
|
| 33 |
+
|
| 34 |
+
```json
|
| 35 |
+
{
|
| 36 |
+
"title": "帳簿のタイトル(ある場合。なければ null)",
|
| 37 |
+
"tables": [
|
| 38 |
+
{
|
| 39 |
+
"headers": ["列名1", "列名2", "列名3"],
|
| 40 |
+
"rows": [
|
| 41 |
+
["セル1", "セル2", "セル3"]
|
| 42 |
+
]
|
| 43 |
+
}
|
| 44 |
+
]
|
| 45 |
+
}
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
注意事項:
|
| 49 |
+
- 数字は半角で出力してください
|
| 50 |
+
- 日付は記載通りに出力してください
|
| 51 |
+
- 判読できない箇所は「???」と記載してください
|
| 52 |
+
- 表が複数ある場合は tables 配列に複数のオブジェクトを含めてください
|
| 53 |
+
- JSONのみを出力してください(前後の説明文は不要です)"""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@ledger_bp.route("/")
|
| 57 |
+
def index():
|
| 58 |
+
"""表 OCR ページを返す。"""
|
| 59 |
+
return render_template("ledger/index.html")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@ledger_bp.route("/process", methods=["POST"])
|
| 63 |
+
def process():
|
| 64 |
+
"""
|
| 65 |
+
画像を受け取り、Qwen3-VL で表データを抽出して Excel に変換する。
|
| 66 |
+
進捗を SSE でストリーミングし、完了後にダウンロード URL を返す。
|
| 67 |
+
|
| 68 |
+
Form data:
|
| 69 |
+
image (file): アップロード画像(任意)
|
| 70 |
+
image_path (str): 画像ファイルパス(任意)
|
| 71 |
+
※ どちらか一方を指定
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
text/event-stream: 進捗メッセージ → {"done": True, "download": "/ledger/download/<filename>"}
|
| 75 |
+
"""
|
| 76 |
+
# 画像の取得(アップロード優先、なければパス指定)
|
| 77 |
+
image_file = request.files.get("image")
|
| 78 |
+
image_path_str = request.form.get("image_path", "").strip()
|
| 79 |
+
|
| 80 |
+
# SSEジェネレータの遅延実行時にリクエストストリームが閉じられる問題を防ぐため、
|
| 81 |
+
# ここでバイト列として先読みしておく
|
| 82 |
+
image_bytes: bytes | None = None
|
| 83 |
+
if image_file and image_file.filename:
|
| 84 |
+
image_bytes = image_file.read()
|
| 85 |
+
|
| 86 |
+
def generate():
|
| 87 |
+
with _model_lock:
|
| 88 |
+
try:
|
| 89 |
+
# ── 画像読み込み ──
|
| 90 |
+
yield sse_event({"progress": "画像を読み込み中...", "step": 1})
|
| 91 |
+
|
| 92 |
+
if image_bytes:
|
| 93 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 94 |
+
elif image_path_str:
|
| 95 |
+
p = Path(image_path_str)
|
| 96 |
+
if not p.exists():
|
| 97 |
+
yield sse_event({"error": f"ファイルが見つかりません: {image_path_str}"})
|
| 98 |
+
return
|
| 99 |
+
image = Image.open(p).convert("RGB")
|
| 100 |
+
else:
|
| 101 |
+
yield sse_event({"error": "画像をアップロードするか、パスを入力してください。"})
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
# ── モデルロード ──
|
| 105 |
+
yield sse_event({"progress": "モデルをロード中(初回のみ数分かかります)...", "step": 2})
|
| 106 |
+
processor, model = get_qwen_model()
|
| 107 |
+
device = next(model.parameters()).device
|
| 108 |
+
|
| 109 |
+
# ── OCR 実行 ──
|
| 110 |
+
yield sse_event({"progress": "表データを解析中(しばらくお待ちください)...", "step": 3})
|
| 111 |
+
|
| 112 |
+
import torch
|
| 113 |
+
|
| 114 |
+
messages = [
|
| 115 |
+
{
|
| 116 |
+
"role": "user",
|
| 117 |
+
"content": [
|
| 118 |
+
{"type": "image"},
|
| 119 |
+
{"type": "text", "text": OCR_PROMPT},
|
| 120 |
+
],
|
| 121 |
+
}
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
text_input = processor.apply_chat_template(
|
| 125 |
+
messages,
|
| 126 |
+
tokenize=False,
|
| 127 |
+
add_generation_prompt=True,
|
| 128 |
+
)
|
| 129 |
+
inputs = processor(
|
| 130 |
+
images=[image],
|
| 131 |
+
text=[text_input],
|
| 132 |
+
padding=True,
|
| 133 |
+
return_tensors="pt",
|
| 134 |
+
)
|
| 135 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 136 |
+
|
| 137 |
+
with torch.no_grad():
|
| 138 |
+
generated_ids = model.generate(
|
| 139 |
+
**inputs,
|
| 140 |
+
max_new_tokens=2048,
|
| 141 |
+
do_sample=False,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
generated_ids_trimmed = [
|
| 145 |
+
out_ids[len(in_ids):]
|
| 146 |
+
for in_ids, out_ids in zip(inputs["input_ids"], generated_ids)
|
| 147 |
+
]
|
| 148 |
+
result_text = processor.batch_decode(
|
| 149 |
+
generated_ids_trimmed,
|
| 150 |
+
skip_special_tokens=True,
|
| 151 |
+
clean_up_tokenization_spaces=False,
|
| 152 |
+
)[0]
|
| 153 |
+
|
| 154 |
+
# ── JSON → Excel 変換 ──
|
| 155 |
+
yield sse_event({"progress": "Excel ファイルを生成中...", "step": 4})
|
| 156 |
+
|
| 157 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 158 |
+
output_filename = f"ledger_{timestamp}.xlsx"
|
| 159 |
+
output_path = OUTPUT_DIR / output_filename
|
| 160 |
+
|
| 161 |
+
parsed = _extract_json(result_text)
|
| 162 |
+
if parsed:
|
| 163 |
+
_save_to_excel(parsed, output_path)
|
| 164 |
+
else:
|
| 165 |
+
_fallback_save(result_text, output_path)
|
| 166 |
+
|
| 167 |
+
yield sse_event({
|
| 168 |
+
"done": True,
|
| 169 |
+
"download": f"/ledger/download/{output_filename}",
|
| 170 |
+
"filename": output_filename,
|
| 171 |
+
})
|
| 172 |
+
|
| 173 |
+
except Exception as exc:
|
| 174 |
+
yield sse_event({"error": f"処理エラー: {exc}"})
|
| 175 |
+
|
| 176 |
+
response = Response(stream_with_context(generate()), mimetype="text/event-stream")
|
| 177 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 178 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 179 |
+
return response
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@ledger_bp.route("/download/<filename>")
|
| 183 |
+
def download(filename: str):
|
| 184 |
+
"""
|
| 185 |
+
生成済み Excel ファイルをダウンロードとして提供する。
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
filename: ファイル名(ledger_YYYYMMDD_HHMMSS.xlsx 形式のみ許可)
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
Excel ファイルのダウンロードレスポンス
|
| 192 |
+
"""
|
| 193 |
+
# パストラバーサル防止:ファイル名のみ許可
|
| 194 |
+
safe_name = Path(filename).name
|
| 195 |
+
if not re.match(r'^ledger_\d{8}_\d{6}\.xlsx$', safe_name):
|
| 196 |
+
return "ファイルが見つかりません", 404
|
| 197 |
+
|
| 198 |
+
file_path = OUTPUT_DIR / safe_name
|
| 199 |
+
if not file_path.exists():
|
| 200 |
+
return "ファイルが見つかりません", 404
|
| 201 |
+
|
| 202 |
+
return send_file(
|
| 203 |
+
file_path,
|
| 204 |
+
as_attachment=True,
|
| 205 |
+
download_name=safe_name,
|
| 206 |
+
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# ── Excel 書き出しユーティリティ ──────────────────────────────────────────
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _extract_json(text: str) -> dict | None:
|
| 214 |
+
"""
|
| 215 |
+
モデル出力テキストから JSON オブジェクトを抽出する。
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
text: モデルが生成したテキスト
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
dict | None: パース済み JSON、失敗時は None
|
| 222 |
+
"""
|
| 223 |
+
for pattern in [r'```json\s*([\s\S]*?)\s*```', r'```\s*([\s\S]*?)\s*```', r'(\{[\s\S]*\})']:
|
| 224 |
+
m = re.search(pattern, text)
|
| 225 |
+
if m:
|
| 226 |
+
try:
|
| 227 |
+
return json.loads(m.group(1))
|
| 228 |
+
except json.JSONDecodeError:
|
| 229 |
+
pass
|
| 230 |
+
return None
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _try_numeric(value: str):
|
| 234 |
+
"""
|
| 235 |
+
文字列を int → float の順で変換を試み、失敗時は元の文字列を返す。
|
| 236 |
+
|
| 237 |
+
Args:
|
| 238 |
+
value: セルの値文字列
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
int | float | str: 変換後の値
|
| 242 |
+
"""
|
| 243 |
+
if not isinstance(value, str):
|
| 244 |
+
return value
|
| 245 |
+
cleaned = value.replace(",", "").replace(",", "")
|
| 246 |
+
try:
|
| 247 |
+
return int(cleaned)
|
| 248 |
+
except ValueError:
|
| 249 |
+
pass
|
| 250 |
+
try:
|
| 251 |
+
return float(cleaned)
|
| 252 |
+
except ValueError:
|
| 253 |
+
pass
|
| 254 |
+
return value
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _save_to_excel(data: dict, output_path: Path) -> None:
|
| 258 |
+
"""
|
| 259 |
+
JSON データを整形した Excel ファイルに書き出す。
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
data: 抽出済み JSON 辞書 (title, tables キーを持つ)
|
| 263 |
+
output_path: 保存先パス
|
| 264 |
+
"""
|
| 265 |
+
import openpyxl
|
| 266 |
+
from openpyxl.styles import Font, PatternFill, Alignment
|
| 267 |
+
|
| 268 |
+
HEADER_FILL = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
|
| 269 |
+
ROW_FILL_ODD = PatternFill(start_color="DCE6F1", end_color="DCE6F1", fill_type="solid")
|
| 270 |
+
|
| 271 |
+
wb = openpyxl.Workbook()
|
| 272 |
+
book_title = data.get("title")
|
| 273 |
+
tables = data.get("tables", [])
|
| 274 |
+
|
| 275 |
+
if not tables:
|
| 276 |
+
raise ValueError("tables キーが空です。")
|
| 277 |
+
|
| 278 |
+
for idx, table in enumerate(tables):
|
| 279 |
+
ws = wb.active if idx == 0 else wb.create_sheet()
|
| 280 |
+
ws.title = f"帳簿{idx + 1}"
|
| 281 |
+
row_ptr = 1
|
| 282 |
+
|
| 283 |
+
if book_title and idx == 0:
|
| 284 |
+
title_cell = ws.cell(row=row_ptr, column=1, value=book_title)
|
| 285 |
+
title_cell.font = Font(bold=True, size=14)
|
| 286 |
+
row_ptr += 2
|
| 287 |
+
|
| 288 |
+
headers = table.get("headers", [])
|
| 289 |
+
rows = table.get("rows", [])
|
| 290 |
+
|
| 291 |
+
for col_idx, header in enumerate(headers, start=1):
|
| 292 |
+
cell = ws.cell(row=row_ptr, column=col_idx, value=header)
|
| 293 |
+
cell.font = Font(bold=True, color="FFFFFF")
|
| 294 |
+
cell.fill = HEADER_FILL
|
| 295 |
+
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 296 |
+
row_ptr += 1
|
| 297 |
+
|
| 298 |
+
for row_num, row_data in enumerate(rows):
|
| 299 |
+
fill = ROW_FILL_ODD if row_num % 2 == 0 else None
|
| 300 |
+
for col_idx, raw_value in enumerate(row_data, start=1):
|
| 301 |
+
value = _try_numeric(raw_value)
|
| 302 |
+
cell = ws.cell(row=row_ptr, column=col_idx, value=value)
|
| 303 |
+
cell.alignment = Alignment(vertical="center", wrap_text=True)
|
| 304 |
+
if fill:
|
| 305 |
+
cell.fill = fill
|
| 306 |
+
if isinstance(value, (int, float)):
|
| 307 |
+
cell.alignment = Alignment(horizontal="right", vertical="center")
|
| 308 |
+
row_ptr += 1
|
| 309 |
+
|
| 310 |
+
for row in ws.iter_rows():
|
| 311 |
+
ws.row_dimensions[row[0].row].height = 18
|
| 312 |
+
|
| 313 |
+
for col in ws.columns:
|
| 314 |
+
max_len = 0
|
| 315 |
+
col_letter = col[0].column_letter
|
| 316 |
+
for cell in col:
|
| 317 |
+
if cell.value:
|
| 318 |
+
w = sum(2 if ord(c) > 127 else 1 for c in str(cell.value))
|
| 319 |
+
max_len = max(max_len, w)
|
| 320 |
+
ws.column_dimensions[col_letter].width = min(max_len + 4, 50)
|
| 321 |
+
|
| 322 |
+
header_row = 1 if not book_title else 3
|
| 323 |
+
ws.freeze_panes = ws.cell(row=header_row + 1, column=1)
|
| 324 |
+
|
| 325 |
+
wb.save(str(output_path))
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def _fallback_save(text: str, output_path: Path) -> None:
|
| 329 |
+
"""
|
| 330 |
+
JSON パース失敗時のフォールバック: テキストをそのまま Excel に保存する。
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
text: モデルの生出力テキスト
|
| 334 |
+
output_path: 保存先パス
|
| 335 |
+
"""
|
| 336 |
+
import openpyxl
|
| 337 |
+
from openpyxl.styles import Font
|
| 338 |
+
|
| 339 |
+
wb = openpyxl.Workbook()
|
| 340 |
+
ws = wb.active
|
| 341 |
+
ws.title = "OCR結果(テキスト)"
|
| 342 |
+
ws.cell(row=1, column=1, value="OCR結果(JSON解析失敗)").font = Font(bold=True, size=12)
|
| 343 |
+
for i, line in enumerate(text.splitlines(), start=2):
|
| 344 |
+
ws.cell(row=i, column=1, value=line)
|
| 345 |
+
ws.column_dimensions["A"].width = 80
|
| 346 |
+
wb.save(str(output_path))
|
MM_tools/app/blueprints/ledger/templates/ledger/index.html
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}表 OCR → Excel - AI Tools{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block head %}
|
| 6 |
+
<style>
|
| 7 |
+
#drop-zone.drag-over {
|
| 8 |
+
border-color: #059669;
|
| 9 |
+
background-color: #d1fae5;
|
| 10 |
+
}
|
| 11 |
+
.step-active { background-color: #059669; color: white; }
|
| 12 |
+
.step-pending { background-color: #e5e7eb; color: #9ca3af; }
|
| 13 |
+
.step-done { background-color: #d1fae5; color: #059669; border: 2px solid #059669; }
|
| 14 |
+
</style>
|
| 15 |
+
{% endblock %}
|
| 16 |
+
|
| 17 |
+
{% block content %}
|
| 18 |
+
<main class="max-w-6xl mx-auto px-6 py-8">
|
| 19 |
+
|
| 20 |
+
<!-- ページタイトル -->
|
| 21 |
+
<div class="flex items-center gap-3 mb-6">
|
| 22 |
+
<div class="w-9 h-9 rounded-lg bg-emerald-700 flex items-center justify-center">
|
| 23 |
+
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 24 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 25 |
+
d="M3 10h18M3 14h18M10 4v16M6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z" />
|
| 26 |
+
</svg>
|
| 27 |
+
</div>
|
| 28 |
+
<div>
|
| 29 |
+
<h1 class="text-2xl font-bold text-gray-900">表 OCR → Excel 出力</h1>
|
| 30 |
+
<p class="text-sm text-gray-400">Qwen3-VL-2B で帳簿・表を解析して Excel ファイルを生成</p>
|
| 31 |
+
</div>
|
| 32 |
+
</div>
|
| 33 |
+
|
| 34 |
+
<div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
|
| 35 |
+
|
| 36 |
+
<!-- ===== 左カラム(3/5): 入力 + 処理 ===== -->
|
| 37 |
+
<div class="lg:col-span-3 flex flex-col gap-5">
|
| 38 |
+
|
| 39 |
+
<!-- 機能説明カード -->
|
| 40 |
+
<div class="bg-emerald-50 border border-emerald-200 rounded-xl p-4">
|
| 41 |
+
<div class="flex items-start gap-3">
|
| 42 |
+
<svg class="w-8 h-8 text-emerald-600 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 43 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 44 |
+
d="M9 12.75l3 3m0 0l3-3m-3 3v-7.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
| 45 |
+
</svg>
|
| 46 |
+
<div>
|
| 47 |
+
<p class="text-sm font-semibold text-emerald-800 mb-1">使い方</p>
|
| 48 |
+
<ol class="text-xs text-emerald-700 space-y-1 list-decimal list-inside">
|
| 49 |
+
<li>帳簿・表が写った画像をアップロード(またはパスを入力)</li>
|
| 50 |
+
<li>「Excel を生成」ボタンをクリック</li>
|
| 51 |
+
<li>解析完了後、Excel ファイルをダウンロード</li>
|
| 52 |
+
</ol>
|
| 53 |
+
</div>
|
| 54 |
+
</div>
|
| 55 |
+
</div>
|
| 56 |
+
|
| 57 |
+
<!-- 画像アップロードエリア -->
|
| 58 |
+
<div>
|
| 59 |
+
<label class="block text-sm font-semibold text-gray-600 mb-2">
|
| 60 |
+
画像のアップロード
|
| 61 |
+
</label>
|
| 62 |
+
<div id="drop-zone"
|
| 63 |
+
class="relative border-2 border-dashed border-emerald-300 rounded-xl bg-emerald-50
|
| 64 |
+
flex flex-col items-center justify-center min-h-[260px] cursor-pointer
|
| 65 |
+
transition-colors duration-200 hover:border-emerald-500 hover:bg-emerald-100">
|
| 66 |
+
|
| 67 |
+
<input type="file" id="image-input" accept="image/*" class="hidden" />
|
| 68 |
+
<img id="preview" class="hidden max-w-full max-h-52 object-contain rounded-lg shadow-sm" />
|
| 69 |
+
|
| 70 |
+
<div id="upload-placeholder" class="text-center px-6 py-8 select-none">
|
| 71 |
+
<div class="w-16 h-16 mx-auto mb-4 rounded-full bg-emerald-200 flex items-center justify-center">
|
| 72 |
+
<svg class="w-8 h-8 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 73 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 74 |
+
d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
|
| 75 |
+
</svg>
|
| 76 |
+
</div>
|
| 77 |
+
<p class="text-emerald-800 font-medium text-sm">クリックまたはドラッグ&ドロップ</p>
|
| 78 |
+
<p class="text-gray-400 text-xs mt-1">PNG, JPG, WEBP など</p>
|
| 79 |
+
</div>
|
| 80 |
+
|
| 81 |
+
<button id="change-btn"
|
| 82 |
+
class="hidden absolute top-3 right-3 text-xs bg-white text-emerald-700 border border-emerald-300
|
| 83 |
+
px-2 py-1 rounded-md shadow-sm hover:bg-emerald-50 transition-colors">
|
| 84 |
+
変更
|
| 85 |
+
</button>
|
| 86 |
+
</div>
|
| 87 |
+
</div>
|
| 88 |
+
|
| 89 |
+
<!-- または: ファイルパス入力 -->
|
| 90 |
+
<div>
|
| 91 |
+
<label class="block text-sm font-semibold text-gray-600 mb-2">
|
| 92 |
+
または、ファイルパスを入力
|
| 93 |
+
</label>
|
| 94 |
+
<div class="flex gap-2">
|
| 95 |
+
<input id="path-input" type="text"
|
| 96 |
+
placeholder="例: C:\Users\user\Desktop\ledger.jpg"
|
| 97 |
+
class="flex-1 text-sm border border-gray-200 rounded-xl px-4 py-2.5
|
| 98 |
+
focus:outline-none focus:ring-2 focus:ring-emerald-400 focus:border-transparent
|
| 99 |
+
placeholder-gray-300 transition" />
|
| 100 |
+
</div>
|
| 101 |
+
<p class="text-xs text-gray-400 mt-1">
|
| 102 |
+
※ アップロード画像がある場合はそちらが優先されます
|
| 103 |
+
</p>
|
| 104 |
+
</div>
|
| 105 |
+
|
| 106 |
+
<!-- 実行ボタン -->
|
| 107 |
+
<button id="run-btn"
|
| 108 |
+
class="flex items-center justify-center gap-2 bg-emerald-700 hover:bg-emerald-800 active:bg-emerald-900
|
| 109 |
+
text-white font-semibold py-3.5 px-8 rounded-xl transition-colors duration-200
|
| 110 |
+
disabled:opacity-50 disabled:cursor-not-allowed shadow-sm">
|
| 111 |
+
<svg id="btn-icon-run" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 112 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 113 |
+
d="M9 12.75l3 3m0 0l3-3m-3 3v-7.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
| 114 |
+
</svg>
|
| 115 |
+
<svg id="btn-icon-spin" class="hidden w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 116 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 117 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 118 |
+
</svg>
|
| 119 |
+
<span id="btn-label">Excel を生成</span>
|
| 120 |
+
</button>
|
| 121 |
+
|
| 122 |
+
</div>
|
| 123 |
+
|
| 124 |
+
<!-- ===== 右カラム(2/5): 進捗 + ダウンロード ===== -->
|
| 125 |
+
<div class="lg:col-span-2 flex flex-col gap-5">
|
| 126 |
+
|
| 127 |
+
<!-- 処理ステップ -->
|
| 128 |
+
<div class="bg-white border border-gray-100 rounded-xl p-5 shadow-sm">
|
| 129 |
+
<h3 class="text-sm font-semibold text-gray-600 mb-4">処理ステップ</h3>
|
| 130 |
+
<div class="space-y-3">
|
| 131 |
+
<div class="flex items-center gap-3">
|
| 132 |
+
<div id="step-1" class="w-7 h-7 rounded-full step-pending flex items-center justify-center text-xs font-bold shrink-0 transition-all">1</div>
|
| 133 |
+
<div>
|
| 134 |
+
<p class="text-sm font-medium text-gray-700">画像の読み込み</p>
|
| 135 |
+
<p class="text-xs text-gray-400">画像ファイルを開きます</p>
|
| 136 |
+
</div>
|
| 137 |
+
</div>
|
| 138 |
+
<div class="flex items-center gap-3">
|
| 139 |
+
<div id="step-2" class="w-7 h-7 rounded-full step-pending flex items-center justify-center text-xs font-bold shrink-0 transition-all">2</div>
|
| 140 |
+
<div>
|
| 141 |
+
<p class="text-sm font-medium text-gray-700">モデルのロード</p>
|
| 142 |
+
<p class="text-xs text-gray-400">初回のみ数分かかります</p>
|
| 143 |
+
</div>
|
| 144 |
+
</div>
|
| 145 |
+
<div class="flex items-center gap-3">
|
| 146 |
+
<div id="step-3" class="w-7 h-7 rounded-full step-pending flex items-center justify-center text-xs font-bold shrink-0 transition-all">3</div>
|
| 147 |
+
<div>
|
| 148 |
+
<p class="text-sm font-medium text-gray-700">表データの解析</p>
|
| 149 |
+
<p class="text-xs text-gray-400">Qwen3-VL で OCR・JSON 抽出</p>
|
| 150 |
+
</div>
|
| 151 |
+
</div>
|
| 152 |
+
<div class="flex items-center gap-3">
|
| 153 |
+
<div id="step-4" class="w-7 h-7 rounded-full step-pending flex items-center justify-center text-xs font-bold shrink-0 transition-all">4</div>
|
| 154 |
+
<div>
|
| 155 |
+
<p class="text-sm font-medium text-gray-700">Excel ファイルの生成</p>
|
| 156 |
+
<p class="text-xs text-gray-400">openpyxl で書き出します</p>
|
| 157 |
+
</div>
|
| 158 |
+
</div>
|
| 159 |
+
</div>
|
| 160 |
+
|
| 161 |
+
<!-- ステータスメッセージ -->
|
| 162 |
+
<p id="status-msg" class="mt-4 text-xs text-gray-400 min-h-[18px]"></p>
|
| 163 |
+
</div>
|
| 164 |
+
|
| 165 |
+
<!-- ダウンロードカード(完了後に表示) -->
|
| 166 |
+
<div id="download-card" class="hidden bg-emerald-50 border border-emerald-300 rounded-xl p-5 shadow-sm">
|
| 167 |
+
<div class="flex items-center gap-3 mb-4">
|
| 168 |
+
<div class="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center">
|
| 169 |
+
<svg class="w-6 h-6 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 170 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 171 |
+
d="M9 12.75l3 3m0 0l3-3m-3 3v-7.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
| 172 |
+
</svg>
|
| 173 |
+
</div>
|
| 174 |
+
<div>
|
| 175 |
+
<p class="text-sm font-bold text-emerald-800">生成完了!</p>
|
| 176 |
+
<p id="download-filename" class="text-xs text-emerald-600 font-mono"></p>
|
| 177 |
+
</div>
|
| 178 |
+
</div>
|
| 179 |
+
<a id="download-link" href="#"
|
| 180 |
+
class="flex items-center justify-center gap-2 bg-emerald-700 hover:bg-emerald-800
|
| 181 |
+
text-white font-semibold py-2.5 px-6 rounded-lg transition-colors w-full text-sm">
|
| 182 |
+
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 183 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 184 |
+
d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M12 3v13.5m0 0l-4.5-4.5M12 16.5l4.5-4.5" />
|
| 185 |
+
</svg>
|
| 186 |
+
Excel をダウンロード
|
| 187 |
+
</a>
|
| 188 |
+
</div>
|
| 189 |
+
|
| 190 |
+
<!-- エラーカード -->
|
| 191 |
+
<div id="error-card" class="hidden bg-red-50 border border-red-200 rounded-xl p-4 shadow-sm">
|
| 192 |
+
<div class="flex items-start gap-2">
|
| 193 |
+
<svg class="w-5 h-5 text-red-500 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 194 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 195 |
+
d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
|
| 196 |
+
</svg>
|
| 197 |
+
<div>
|
| 198 |
+
<p class="text-sm font-semibold text-red-700">エラーが発生しました</p>
|
| 199 |
+
<p id="error-msg" class="text-xs text-red-600 mt-1"></p>
|
| 200 |
+
</div>
|
| 201 |
+
</div>
|
| 202 |
+
</div>
|
| 203 |
+
|
| 204 |
+
<!-- 対応形式 -->
|
| 205 |
+
<div class="bg-white border border-gray-100 rounded-xl p-4 shadow-sm">
|
| 206 |
+
<h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">対応画像形式</h3>
|
| 207 |
+
<div class="flex flex-wrap gap-2">
|
| 208 |
+
<span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-md font-mono">JPG</span>
|
| 209 |
+
<span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-md font-mono">PNG</span>
|
| 210 |
+
<span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-md font-mono">WEBP</span>
|
| 211 |
+
<span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-md font-mono">BMP</span>
|
| 212 |
+
<span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-md font-mono">TIFF</span>
|
| 213 |
+
</div>
|
| 214 |
+
<h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mt-3 mb-2">精度を上げるコツ</h3>
|
| 215 |
+
<ul class="text-xs text-gray-500 space-y-1">
|
| 216 |
+
<li>• 表全体が収まるように撮影</li>
|
| 217 |
+
<li>• 十分な明るさで水平に撮影</li>
|
| 218 |
+
<li>• 解像度は高いほど精度が向上</li>
|
| 219 |
+
</ul>
|
| 220 |
+
</div>
|
| 221 |
+
|
| 222 |
+
</div>
|
| 223 |
+
|
| 224 |
+
</div><!-- /grid -->
|
| 225 |
+
</main>
|
| 226 |
+
|
| 227 |
+
<script>
|
| 228 |
+
// ── DOM 参照 ────────────────────────────────────────────────────
|
| 229 |
+
const dropZone = document.getElementById('drop-zone');
|
| 230 |
+
const imageInput = document.getElementById('image-input');
|
| 231 |
+
const preview = document.getElementById('preview');
|
| 232 |
+
const uploadPh = document.getElementById('upload-placeholder');
|
| 233 |
+
const changeBtn = document.getElementById('change-btn');
|
| 234 |
+
const pathInput = document.getElementById('path-input');
|
| 235 |
+
const runBtn = document.getElementById('run-btn');
|
| 236 |
+
const btnLabel = document.getElementById('btn-label');
|
| 237 |
+
const btnIconRun = document.getElementById('btn-icon-run');
|
| 238 |
+
const btnIconSpin = document.getElementById('btn-icon-spin');
|
| 239 |
+
const statusMsg = document.getElementById('status-msg');
|
| 240 |
+
const downloadCard = document.getElementById('download-card');
|
| 241 |
+
const downloadLink = document.getElementById('download-link');
|
| 242 |
+
const downloadFilename = document.getElementById('download-filename');
|
| 243 |
+
const errorCard = document.getElementById('error-card');
|
| 244 |
+
const errorMsg = document.getElementById('error-msg');
|
| 245 |
+
|
| 246 |
+
const steps = [1, 2, 3, 4].map(i => document.getElementById(`step-${i}`));
|
| 247 |
+
|
| 248 |
+
// ── 画像アップロード ────────────────────────────────────────────
|
| 249 |
+
dropZone.addEventListener('click', (e) => {
|
| 250 |
+
if (e.target === changeBtn) return;
|
| 251 |
+
imageInput.click();
|
| 252 |
+
});
|
| 253 |
+
changeBtn.addEventListener('click', (e) => {
|
| 254 |
+
e.stopPropagation();
|
| 255 |
+
imageInput.click();
|
| 256 |
+
});
|
| 257 |
+
imageInput.addEventListener('change', (e) => {
|
| 258 |
+
if (e.target.files[0]) showPreview(e.target.files[0]);
|
| 259 |
+
});
|
| 260 |
+
dropZone.addEventListener('dragover', (e) => {
|
| 261 |
+
e.preventDefault();
|
| 262 |
+
dropZone.classList.add('drag-over');
|
| 263 |
+
});
|
| 264 |
+
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
|
| 265 |
+
dropZone.addEventListener('drop', (e) => {
|
| 266 |
+
e.preventDefault();
|
| 267 |
+
dropZone.classList.remove('drag-over');
|
| 268 |
+
const file = e.dataTransfer.files[0];
|
| 269 |
+
if (file && file.type.startsWith('image/')) {
|
| 270 |
+
showPreview(file);
|
| 271 |
+
const dt = new DataTransfer();
|
| 272 |
+
dt.items.add(file);
|
| 273 |
+
imageInput.files = dt.files;
|
| 274 |
+
}
|
| 275 |
+
});
|
| 276 |
+
|
| 277 |
+
function showPreview(file) {
|
| 278 |
+
const reader = new FileReader();
|
| 279 |
+
reader.onload = (e) => {
|
| 280 |
+
preview.src = e.target.result;
|
| 281 |
+
preview.classList.remove('hidden');
|
| 282 |
+
uploadPh.classList.add('hidden');
|
| 283 |
+
changeBtn.classList.remove('hidden');
|
| 284 |
+
};
|
| 285 |
+
reader.readAsDataURL(file);
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
// ── ステップ表示 ────────────────────────────────────────────────
|
| 289 |
+
function setStep(step) {
|
| 290 |
+
steps.forEach((el, i) => {
|
| 291 |
+
el.className = 'w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-all ' +
|
| 292 |
+
(i + 1 < step ? 'step-done' :
|
| 293 |
+
i + 1 === step ? 'step-active' : 'step-pending');
|
| 294 |
+
if (i + 1 < step) {
|
| 295 |
+
el.innerHTML = `<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
|
| 296 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>`;
|
| 297 |
+
} else {
|
| 298 |
+
el.textContent = i + 1;
|
| 299 |
+
}
|
| 300 |
+
});
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
// ── SSE パーサー ────────────────────────────────────────────────
|
| 304 |
+
async function consumeSSE(response, onData) {
|
| 305 |
+
const reader = response.body.getReader();
|
| 306 |
+
const decoder = new TextDecoder();
|
| 307 |
+
let buffer = '';
|
| 308 |
+
while (true) {
|
| 309 |
+
const { done, value } = await reader.read();
|
| 310 |
+
if (done) break;
|
| 311 |
+
buffer += decoder.decode(value, { stream: true });
|
| 312 |
+
const lines = buffer.split('\n');
|
| 313 |
+
buffer = lines.pop();
|
| 314 |
+
for (const line of lines) {
|
| 315 |
+
if (!line.startsWith('data: ')) continue;
|
| 316 |
+
try { onData(JSON.parse(line.slice(6))); } catch { /* ignore */ }
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
// ── 実行 ────────────────────────────────────────────────────────
|
| 322 |
+
runBtn.addEventListener('click', async () => {
|
| 323 |
+
const hasFile = imageInput.files.length > 0;
|
| 324 |
+
const hasPath = pathInput.value.trim() !== '';
|
| 325 |
+
|
| 326 |
+
if (!hasFile && !hasPath) {
|
| 327 |
+
alert('画像をアップロードするか、ファイルパスを入力してください。');
|
| 328 |
+
return;
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
setLoading(true);
|
| 332 |
+
downloadCard.classList.add('hidden');
|
| 333 |
+
errorCard.classList.add('hidden');
|
| 334 |
+
statusMsg.textContent = '';
|
| 335 |
+
setStep(0);
|
| 336 |
+
|
| 337 |
+
const formData = new FormData();
|
| 338 |
+
if (hasFile) formData.append('image', imageInput.files[0]);
|
| 339 |
+
if (hasPath) formData.append('image_path', pathInput.value.trim());
|
| 340 |
+
|
| 341 |
+
try {
|
| 342 |
+
const response = await fetch('/ledger/process', { method: 'POST', body: formData });
|
| 343 |
+
if (!response.ok) throw new Error(`HTTP エラー: ${response.status}`);
|
| 344 |
+
|
| 345 |
+
await consumeSSE(response, (data) => {
|
| 346 |
+
if (data.progress) {
|
| 347 |
+
statusMsg.textContent = data.progress;
|
| 348 |
+
if (data.step) setStep(data.step);
|
| 349 |
+
}
|
| 350 |
+
if (data.done) {
|
| 351 |
+
setStep(5);
|
| 352 |
+
statusMsg.textContent = '完了!';
|
| 353 |
+
downloadLink.href = data.download;
|
| 354 |
+
downloadFilename.textContent = data.filename;
|
| 355 |
+
downloadCard.classList.remove('hidden');
|
| 356 |
+
}
|
| 357 |
+
if (data.error) {
|
| 358 |
+
errorMsg.textContent = data.error;
|
| 359 |
+
errorCard.classList.remove('hidden');
|
| 360 |
+
statusMsg.textContent = 'エラーが発生しました';
|
| 361 |
+
}
|
| 362 |
+
});
|
| 363 |
+
} catch (err) {
|
| 364 |
+
errorMsg.textContent = err.message;
|
| 365 |
+
errorCard.classList.remove('hidden');
|
| 366 |
+
} finally {
|
| 367 |
+
setLoading(false);
|
| 368 |
+
}
|
| 369 |
+
});
|
| 370 |
+
|
| 371 |
+
// ── UI 状態管理 ─────────────────────────────────────────────────
|
| 372 |
+
function setLoading(loading) {
|
| 373 |
+
runBtn.disabled = loading;
|
| 374 |
+
btnLabel.textContent = loading ? '処理中...' : 'Excel を生成';
|
| 375 |
+
btnIconRun.classList.toggle('hidden', loading);
|
| 376 |
+
btnIconSpin.classList.toggle('hidden', !loading);
|
| 377 |
+
}
|
| 378 |
+
</script>
|
| 379 |
+
{% endblock %}
|
MM_tools/app/blueprints/main/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint
|
| 2 |
+
|
| 3 |
+
main_bp = Blueprint(
|
| 4 |
+
"main",
|
| 5 |
+
__name__,
|
| 6 |
+
template_folder="templates",
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
from . import routes # noqa: E402, F401
|
MM_tools/app/blueprints/main/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (337 Bytes). View file
|
|
|
MM_tools/app/blueprints/main/__pycache__/routes.cpython-314.pyc
ADDED
|
Binary file (590 Bytes). View file
|
|
|
MM_tools/app/blueprints/main/routes.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""main ブループリント ルーティング(トップページ)。"""
|
| 2 |
+
|
| 3 |
+
from flask import render_template
|
| 4 |
+
from . import main_bp
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@main_bp.route("/")
|
| 8 |
+
def index():
|
| 9 |
+
"""トップページを返す。"""
|
| 10 |
+
return render_template("main/index.html")
|
MM_tools/app/blueprints/main/templates/main/index.html
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}AI Tools - トップページ{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block content %}
|
| 6 |
+
<main class="max-w-6xl mx-auto px-6 py-12">
|
| 7 |
+
|
| 8 |
+
<!-- ヒーローセクション -->
|
| 9 |
+
<div class="text-center mb-14">
|
| 10 |
+
<div class="inline-flex items-center justify-center w-20 h-20 rounded-2xl bg-indigo-900 mb-6 shadow-lg">
|
| 11 |
+
<svg class="w-10 h-10 text-indigo-200" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 12 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 13 |
+
d="M9.75 3.75H6A2.25 2.25 0 003.75 6v12A2.25 2.25 0 006 20.25h12A2.25 2.25 0 0020.25 18v-3.75M16.5 3.75h3.75v3.75M20.25 3.75L12 12" />
|
| 14 |
+
</svg>
|
| 15 |
+
</div>
|
| 16 |
+
<h1 class="text-4xl font-bold text-gray-900 mb-3">AI Tools</h1>
|
| 17 |
+
<p class="text-gray-500 text-lg max-w-xl mx-auto">
|
| 18 |
+
ローカル AI モデルを使った、翻訳・OCR・帳簿 Excel 化・VLM・音声文字起こしツール
|
| 19 |
+
</p>
|
| 20 |
+
</div>
|
| 21 |
+
|
| 22 |
+
<!-- ツールカード一覧 -->
|
| 23 |
+
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
|
| 24 |
+
|
| 25 |
+
<!-- ① 多言語翻訳 -->
|
| 26 |
+
<a href="/translation"
|
| 27 |
+
class="group flex flex-col bg-white rounded-2xl shadow-sm border border-gray-100
|
| 28 |
+
hover:shadow-md hover:border-indigo-300 transition-all duration-200 overflow-hidden">
|
| 29 |
+
<div class="bg-gradient-to-br from-indigo-500 to-indigo-700 p-8 flex items-center justify-center">
|
| 30 |
+
<svg class="w-14 h-14 text-white opacity-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 31 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 32 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 33 |
+
</svg>
|
| 34 |
+
</div>
|
| 35 |
+
<div class="p-6 flex-1 flex flex-col">
|
| 36 |
+
<div class="flex items-center gap-2 mb-2">
|
| 37 |
+
<span class="text-xs font-bold text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full">① 翻訳</span>
|
| 38 |
+
</div>
|
| 39 |
+
<h2 class="text-xl font-bold text-gray-900 mb-2 group-hover:text-indigo-700 transition-colors">
|
| 40 |
+
多言語翻訳
|
| 41 |
+
</h2>
|
| 42 |
+
<p class="text-sm text-gray-500 flex-1">
|
| 43 |
+
テキストを自由に入力して多言語へ翻訳。日本語・英語ほか、任意の言語を指定できます。
|
| 44 |
+
</p>
|
| 45 |
+
<div class="mt-4 flex items-center gap-1 text-indigo-600 text-sm font-semibold">
|
| 46 |
+
開く
|
| 47 |
+
<svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 48 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
| 49 |
+
</svg>
|
| 50 |
+
</div>
|
| 51 |
+
</div>
|
| 52 |
+
</a>
|
| 53 |
+
|
| 54 |
+
<!-- ② OCR と翻訳 -->
|
| 55 |
+
<a href="/ocr"
|
| 56 |
+
class="group flex flex-col bg-white rounded-2xl shadow-sm border border-gray-100
|
| 57 |
+
hover:shadow-md hover:border-indigo-300 transition-all duration-200 overflow-hidden">
|
| 58 |
+
<div class="bg-gradient-to-br from-violet-500 to-violet-700 p-8 flex items-center justify-center">
|
| 59 |
+
<svg class="w-14 h-14 text-white opacity-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 60 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 61 |
+
d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
|
| 62 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
|
| 63 |
+
</svg>
|
| 64 |
+
</div>
|
| 65 |
+
<div class="p-6 flex-1 flex flex-col">
|
| 66 |
+
<div class="flex items-center gap-2 mb-2">
|
| 67 |
+
<span class="text-xs font-bold text-violet-600 bg-violet-50 px-2 py-0.5 rounded-full">② OCR</span>
|
| 68 |
+
</div>
|
| 69 |
+
<h2 class="text-xl font-bold text-gray-900 mb-2 group-hover:text-violet-700 transition-colors">
|
| 70 |
+
OCR と翻訳
|
| 71 |
+
</h2>
|
| 72 |
+
<p class="text-sm text-gray-500 flex-1">
|
| 73 |
+
画像をアップロードして GLM-OCR でテキスト抽出。抽出結果をそのまま日本語翻訳できます。
|
| 74 |
+
</p>
|
| 75 |
+
<div class="mt-4 flex items-center gap-1 text-violet-600 text-sm font-semibold">
|
| 76 |
+
開く
|
| 77 |
+
<svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 78 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
| 79 |
+
</svg>
|
| 80 |
+
</div>
|
| 81 |
+
</div>
|
| 82 |
+
</a>
|
| 83 |
+
|
| 84 |
+
<!-- ③ 表 OCR → Excel -->
|
| 85 |
+
<a href="/ledger"
|
| 86 |
+
class="group flex flex-col bg-white rounded-2xl shadow-sm border border-gray-100
|
| 87 |
+
hover:shadow-md hover:border-indigo-300 transition-all duration-200 overflow-hidden">
|
| 88 |
+
<div class="bg-gradient-to-br from-emerald-500 to-emerald-700 p-8 flex items-center justify-center">
|
| 89 |
+
<svg class="w-14 h-14 text-white opacity-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 90 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 91 |
+
d="M3 10h18M3 14h18M10 4v16M6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z" />
|
| 92 |
+
</svg>
|
| 93 |
+
</div>
|
| 94 |
+
<div class="p-6 flex-1 flex flex-col">
|
| 95 |
+
<div class="flex items-center gap-2 mb-2">
|
| 96 |
+
<span class="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">③ Excel 出力</span>
|
| 97 |
+
</div>
|
| 98 |
+
<h2 class="text-xl font-bold text-gray-900 mb-2 group-hover:text-emerald-700 transition-colors">
|
| 99 |
+
表 OCR → Excel
|
| 100 |
+
</h2>
|
| 101 |
+
<p class="text-sm text-gray-500 flex-1">
|
| 102 |
+
帳簿・表の画像を Qwen3-VL で解析し、Excel ファイルとしてダウンロードできます。
|
| 103 |
+
</p>
|
| 104 |
+
<div class="mt-4 flex items-center gap-1 text-emerald-600 text-sm font-semibold">
|
| 105 |
+
開く
|
| 106 |
+
<svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 107 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
| 108 |
+
</svg>
|
| 109 |
+
</div>
|
| 110 |
+
</div>
|
| 111 |
+
</a>
|
| 112 |
+
|
| 113 |
+
<!-- ④ VLM -->
|
| 114 |
+
<a href="/vlm"
|
| 115 |
+
class="group flex flex-col bg-white rounded-2xl shadow-sm border border-gray-100
|
| 116 |
+
hover:shadow-md hover:border-amber-300 transition-all duration-200 overflow-hidden">
|
| 117 |
+
<div class="bg-gradient-to-br from-amber-400 to-amber-600 p-8 flex items-center justify-center">
|
| 118 |
+
<svg class="w-14 h-14 text-white opacity-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 119 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 120 |
+
d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909M3 16.5V18a2.25 2.25 0 002.25 2.25h13.5A2.25 2.25 0 0021 18v-1.5M16.5 6.75a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
|
| 121 |
+
</svg>
|
| 122 |
+
</div>
|
| 123 |
+
<div class="p-6 flex-1 flex flex-col">
|
| 124 |
+
<div class="flex items-center gap-2 mb-2">
|
| 125 |
+
<span class="text-xs font-bold text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full">④ VLM</span>
|
| 126 |
+
</div>
|
| 127 |
+
<h2 class="text-xl font-bold text-gray-900 mb-2 group-hover:text-amber-600 transition-colors">
|
| 128 |
+
ビジュアル言語モデル
|
| 129 |
+
</h2>
|
| 130 |
+
<p class="text-sm text-gray-500 flex-1">
|
| 131 |
+
画像とプロンプトで Qwen3-VL に自由に問い合わせ。概要・文字読み取り・HTML テーブル化など。
|
| 132 |
+
</p>
|
| 133 |
+
<div class="mt-4 flex items-center gap-1 text-amber-600 text-sm font-semibold">
|
| 134 |
+
開く
|
| 135 |
+
<svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 136 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
| 137 |
+
</svg>
|
| 138 |
+
</div>
|
| 139 |
+
</div>
|
| 140 |
+
</a>
|
| 141 |
+
|
| 142 |
+
<!-- ⑤ 音声文字起こし -->
|
| 143 |
+
<a href="/whisper"
|
| 144 |
+
class="group flex flex-col bg-white rounded-2xl shadow-sm border border-gray-100
|
| 145 |
+
hover:shadow-md hover:border-cyan-300 transition-all duration-200 overflow-hidden">
|
| 146 |
+
<div class="bg-gradient-to-br from-cyan-500 to-cyan-700 p-8 flex items-center justify-center">
|
| 147 |
+
<svg class="w-14 h-14 text-white opacity-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 148 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 149 |
+
d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
|
| 150 |
+
</svg>
|
| 151 |
+
</div>
|
| 152 |
+
<div class="p-6 flex-1 flex flex-col">
|
| 153 |
+
<div class="flex items-center gap-2 mb-2">
|
| 154 |
+
<span class="text-xs font-bold text-cyan-600 bg-cyan-50 px-2 py-0.5 rounded-full">⑤ 文字起こし</span>
|
| 155 |
+
</div>
|
| 156 |
+
<h2 class="text-xl font-bold text-gray-900 mb-2 group-hover:text-cyan-700 transition-colors">
|
| 157 |
+
音声文字起こし
|
| 158 |
+
</h2>
|
| 159 |
+
<p class="text-sm text-gray-500 flex-1">
|
| 160 |
+
音声・動画ファイルを Whisper で解析。タイムスタンプあり/なしで書き起こしテキストを出力。
|
| 161 |
+
</p>
|
| 162 |
+
<div class="mt-4 flex items-center gap-1 text-cyan-600 text-sm font-semibold">
|
| 163 |
+
開く
|
| 164 |
+
<svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 165 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
| 166 |
+
</svg>
|
| 167 |
+
</div>
|
| 168 |
+
</div>
|
| 169 |
+
</a>
|
| 170 |
+
|
| 171 |
+
</div>
|
| 172 |
+
|
| 173 |
+
<!-- 使用モデル情報 -->
|
| 174 |
+
<div class="mt-12 bg-white border border-gray-100 rounded-2xl p-6 shadow-sm">
|
| 175 |
+
<h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-4">使用モデル</h3>
|
| 176 |
+
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 text-sm">
|
| 177 |
+
<div class="flex items-start gap-3">
|
| 178 |
+
<div class="w-2 h-2 rounded-full bg-indigo-500 mt-1.5 shrink-0"></div>
|
| 179 |
+
<div>
|
| 180 |
+
<p class="font-semibold text-gray-800">多言語翻訳</p>
|
| 181 |
+
<p class="text-gray-400">LFM 2.5 (ONNX)</p>
|
| 182 |
+
</div>
|
| 183 |
+
</div>
|
| 184 |
+
<div class="flex items-start gap-3">
|
| 185 |
+
<div class="w-2 h-2 rounded-full bg-violet-500 mt-1.5 shrink-0"></div>
|
| 186 |
+
<div>
|
| 187 |
+
<p class="font-semibold text-gray-800">OCR と翻訳</p>
|
| 188 |
+
<p class="text-gray-400">GLM-OCR + LFM 2.5</p>
|
| 189 |
+
</div>
|
| 190 |
+
</div>
|
| 191 |
+
<div class="flex items-start gap-3">
|
| 192 |
+
<div class="w-2 h-2 rounded-full bg-emerald-500 mt-1.5 shrink-0"></div>
|
| 193 |
+
<div>
|
| 194 |
+
<p class="font-semibold text-gray-800">表 OCR → Excel</p>
|
| 195 |
+
<p class="text-gray-400">Qwen3-VL-2B-Instruct</p>
|
| 196 |
+
</div>
|
| 197 |
+
</div>
|
| 198 |
+
<div class="flex items-start gap-3">
|
| 199 |
+
<div class="w-2 h-2 rounded-full bg-amber-500 mt-1.5 shrink-0"></div>
|
| 200 |
+
<div>
|
| 201 |
+
<p class="font-semibold text-gray-800">VLM</p>
|
| 202 |
+
<p class="text-gray-400">Qwen3-VL-2B-Instruct</p>
|
| 203 |
+
</div>
|
| 204 |
+
</div>
|
| 205 |
+
<div class="flex items-start gap-3">
|
| 206 |
+
<div class="w-2 h-2 rounded-full bg-cyan-500 mt-1.5 shrink-0"></div>
|
| 207 |
+
<div>
|
| 208 |
+
<p class="font-semibold text-gray-800">音声文字起こし</p>
|
| 209 |
+
<p class="text-gray-400">Whisper Small / Large-v3-turbo</p>
|
| 210 |
+
</div>
|
| 211 |
+
</div>
|
| 212 |
+
</div>
|
| 213 |
+
</div>
|
| 214 |
+
|
| 215 |
+
</main>
|
| 216 |
+
{% endblock %}
|
MM_tools/app/blueprints/ocr/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint
|
| 2 |
+
|
| 3 |
+
ocr_bp = Blueprint(
|
| 4 |
+
"ocr",
|
| 5 |
+
__name__,
|
| 6 |
+
template_folder="templates",
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
from . import routes # noqa: E402, F401
|
MM_tools/app/blueprints/ocr/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (334 Bytes). View file
|
|
|
MM_tools/app/blueprints/ocr/__pycache__/routes.cpython-314.pyc
ADDED
|
Binary file (9.39 kB). View file
|
|
|
MM_tools/app/blueprints/ocr/routes.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ocr ブループリント ルーティング。
|
| 3 |
+
|
| 4 |
+
② OCR と翻訳ページ。
|
| 5 |
+
GLM-OCR で画像からテキストを抽出し、LFM 2.5 (ONNX) で日本語翻訳する。
|
| 6 |
+
両処理とも SSE (Server-Sent Events) でストリーミング送信する。
|
| 7 |
+
ステータスイベント: {"status": "loading"|"processing", "message": "...", "detail": "..."}
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import io
|
| 11 |
+
import threading
|
| 12 |
+
|
| 13 |
+
from flask import render_template, request, Response, stream_with_context
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
from . import ocr_bp
|
| 17 |
+
from app.shared.models import get_glm_model, get_lfm, is_glm_loaded, is_lfm_loaded, get_lfm_lock
|
| 18 |
+
from app.shared.utils import sse_event, resize_image_to_base64
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@ocr_bp.route("/")
|
| 22 |
+
def index():
|
| 23 |
+
"""OCR ページを返す。"""
|
| 24 |
+
return render_template("ocr/index.html")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@ocr_bp.route("/run", methods=["POST"])
|
| 28 |
+
def run_ocr():
|
| 29 |
+
"""
|
| 30 |
+
画像とプロンプトを受け取り、GLM-OCR 結果を SSE でストリーミングする。
|
| 31 |
+
|
| 32 |
+
Form data:
|
| 33 |
+
image (file): アップロード画像
|
| 34 |
+
prompt (str): OCR プロンプト(省略時はデフォルト)
|
| 35 |
+
|
| 36 |
+
SSE イベント:
|
| 37 |
+
{"status": "loading", "message": "...", "detail": "..."} モデルロード中
|
| 38 |
+
{"status": "processing", "message": "...", "detail": "..."} OCR処理中
|
| 39 |
+
{"text": "累積テキスト"} トークンストリーム
|
| 40 |
+
{"done": True} 完了
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
text/event-stream
|
| 44 |
+
"""
|
| 45 |
+
from transformers import TextIteratorStreamer
|
| 46 |
+
|
| 47 |
+
if "image" not in request.files or request.files["image"].filename == "":
|
| 48 |
+
def _err():
|
| 49 |
+
yield sse_event({"error": "画像をアップロードしてください。"})
|
| 50 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 51 |
+
|
| 52 |
+
image_file = request.files["image"]
|
| 53 |
+
prompt = request.form.get("prompt", "").strip()
|
| 54 |
+
if not prompt:
|
| 55 |
+
prompt = "画像内のテキストをすべて読み取ってHTMLとして出力してください。"
|
| 56 |
+
|
| 57 |
+
# ファイルバイトを先読み(ジェネレータ遅延実行時にストリームが閉じる問題を防ぐ)
|
| 58 |
+
try:
|
| 59 |
+
image_bytes = image_file.read()
|
| 60 |
+
except Exception as exc:
|
| 61 |
+
def _err():
|
| 62 |
+
yield sse_event({"error": f"画像の読み込みに失敗しました: {exc}"})
|
| 63 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 64 |
+
|
| 65 |
+
def generate():
|
| 66 |
+
"""モデルロード → OCR → SSE ストリーミングを行うジェネレータ。"""
|
| 67 |
+
# ── 画像を開く ──────────────────────────────────────────────
|
| 68 |
+
try:
|
| 69 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 70 |
+
image_base64 = resize_image_to_base64(image)
|
| 71 |
+
except Exception as exc:
|
| 72 |
+
yield sse_event({"error": f"画像の読み込みに失敗しました: {exc}"})
|
| 73 |
+
return
|
| 74 |
+
|
| 75 |
+
# ── モデルロード状態を通知 ──────────────────────────────────
|
| 76 |
+
if not is_glm_loaded():
|
| 77 |
+
yield sse_event({
|
| 78 |
+
"status": "loading",
|
| 79 |
+
"message": "OCR モデルをロード中...",
|
| 80 |
+
"detail": "初回のみ数分かかります。しばらくお待ちください。",
|
| 81 |
+
})
|
| 82 |
+
else:
|
| 83 |
+
yield sse_event({
|
| 84 |
+
"status": "processing",
|
| 85 |
+
"message": "OCR を開始します...",
|
| 86 |
+
"detail": "",
|
| 87 |
+
})
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
processor, model = get_glm_model()
|
| 91 |
+
except Exception as exc:
|
| 92 |
+
yield sse_event({"error": f"OCR モデルのロードに失敗しました: {exc}"})
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
# ── OCR 処理中を通知 ────────────────────────────────────────
|
| 96 |
+
yield sse_event({
|
| 97 |
+
"status": "processing",
|
| 98 |
+
"message": "OCR 解析中...",
|
| 99 |
+
"detail": "画像からテキストを認識しています",
|
| 100 |
+
})
|
| 101 |
+
|
| 102 |
+
messages = [
|
| 103 |
+
{
|
| 104 |
+
"role": "user",
|
| 105 |
+
"content": [
|
| 106 |
+
{"type": "image", "image": f"data:image/jpeg;base64,{image_base64}"},
|
| 107 |
+
{"type": "text", "text": prompt},
|
| 108 |
+
],
|
| 109 |
+
}
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
inputs = processor.apply_chat_template(
|
| 113 |
+
messages,
|
| 114 |
+
tokenize=True,
|
| 115 |
+
add_generation_prompt=True,
|
| 116 |
+
return_dict=True,
|
| 117 |
+
return_tensors="pt",
|
| 118 |
+
).to(model.device)
|
| 119 |
+
inputs.pop("token_type_ids", None)
|
| 120 |
+
|
| 121 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 122 |
+
generation_kwargs = {**inputs, "max_new_tokens": 5120, "streamer": streamer}
|
| 123 |
+
thread = threading.Thread(target=model.generate, kwargs=generation_kwargs)
|
| 124 |
+
|
| 125 |
+
thread.start()
|
| 126 |
+
output_text = ""
|
| 127 |
+
for token in streamer:
|
| 128 |
+
output_text += token
|
| 129 |
+
yield sse_event({"text": output_text})
|
| 130 |
+
thread.join()
|
| 131 |
+
yield sse_event({"done": True})
|
| 132 |
+
|
| 133 |
+
response = Response(stream_with_context(generate()), mimetype="text/event-stream")
|
| 134 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 135 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 136 |
+
return response
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@ocr_bp.route("/translate", methods=["POST"])
|
| 140 |
+
def translate():
|
| 141 |
+
"""
|
| 142 |
+
OCR テキストを受け取り、LFM 2.5 (ONNX) で日本語翻訳して SSE でストリーミングする。
|
| 143 |
+
|
| 144 |
+
Form data:
|
| 145 |
+
text (str): 翻訳対象のプレーンテキスト(OCR 出力の innerText)
|
| 146 |
+
|
| 147 |
+
SSE イベント:
|
| 148 |
+
{"status": "loading", "message": "...", "detail": "..."} モデルロード中
|
| 149 |
+
{"status": "processing", "message": "...", "detail": "..."} 翻訳処理中
|
| 150 |
+
{"text": "累積テキスト"} トークンストリーム
|
| 151 |
+
{"done": True} 完了
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
text/event-stream
|
| 155 |
+
"""
|
| 156 |
+
text = request.form.get("text", "").strip()
|
| 157 |
+
if not text:
|
| 158 |
+
def _err():
|
| 159 |
+
yield sse_event({"error": "翻訳するテキストがありません。"})
|
| 160 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 161 |
+
|
| 162 |
+
system_prompt = (
|
| 163 |
+
"あなたはプロの翻訳者です。与えられた文章を日本語に翻訳してください。"
|
| 164 |
+
"翻訳文のみを出力してください。説明や補足は不要です。"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def generate():
|
| 168 |
+
"""翻訳トークンを SSE で送信するジェネレータ。"""
|
| 169 |
+
with get_lfm_lock():
|
| 170 |
+
# ── モデルロード状態を通知 ──────────────────────────────
|
| 171 |
+
if not is_lfm_loaded():
|
| 172 |
+
yield sse_event({
|
| 173 |
+
"status": "loading",
|
| 174 |
+
"message": "翻訳モデルをロード中...",
|
| 175 |
+
"detail": "初回のみ数分かかります。しばらくお待ちください。",
|
| 176 |
+
})
|
| 177 |
+
else:
|
| 178 |
+
yield sse_event({
|
| 179 |
+
"status": "processing",
|
| 180 |
+
"message": "翻訳中...",
|
| 181 |
+
"detail": "テキストを日本語に変換しています",
|
| 182 |
+
})
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
llm = get_lfm()
|
| 186 |
+
yield sse_event({
|
| 187 |
+
"status": "processing",
|
| 188 |
+
"message": "翻訳中...",
|
| 189 |
+
"detail": "テキストを日本語に変換しています",
|
| 190 |
+
})
|
| 191 |
+
for chunk in llm.stream(user_prompt=text, system_prompt=system_prompt):
|
| 192 |
+
yield sse_event({"text": chunk})
|
| 193 |
+
yield sse_event({"done": True})
|
| 194 |
+
except Exception as exc:
|
| 195 |
+
yield sse_event({"error": f"翻訳エラー: {exc}"})
|
| 196 |
+
|
| 197 |
+
response = Response(stream_with_context(generate()), mimetype="text/event-stream")
|
| 198 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 199 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 200 |
+
return response
|
MM_tools/app/blueprints/ocr/templates/ocr/index.html
ADDED
|
@@ -0,0 +1,586 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}OCR と翻訳 - AI Tools{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block head %}
|
| 6 |
+
<style>
|
| 7 |
+
#drop-zone.drag-over {
|
| 8 |
+
border-color: #4338ca;
|
| 9 |
+
background-color: #e0e7ff;
|
| 10 |
+
}
|
| 11 |
+
.result-box::-webkit-scrollbar { width: 6px; }
|
| 12 |
+
.result-box::-webkit-scrollbar-track { background: #f1f5f9; }
|
| 13 |
+
.result-box::-webkit-scrollbar-thumb { background: #a5b4fc; border-radius: 3px; }
|
| 14 |
+
</style>
|
| 15 |
+
{% endblock %}
|
| 16 |
+
|
| 17 |
+
{% block content %}
|
| 18 |
+
<main class="max-w-7xl mx-auto px-6 py-8">
|
| 19 |
+
|
| 20 |
+
<!-- ページタイトル -->
|
| 21 |
+
<div class="flex items-center gap-3 mb-6">
|
| 22 |
+
<div class="w-9 h-9 rounded-lg bg-violet-700 flex items-center justify-center">
|
| 23 |
+
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 24 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 25 |
+
d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
|
| 26 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
|
| 27 |
+
</svg>
|
| 28 |
+
</div>
|
| 29 |
+
<div>
|
| 30 |
+
<h1 class="text-2xl font-bold text-gray-900">OCR と翻訳</h1>
|
| 31 |
+
<p class="text-sm text-gray-400">GLM-OCR で文字認識 → LFM 2.5 で日本語翻訳</p>
|
| 32 |
+
</div>
|
| 33 |
+
</div>
|
| 34 |
+
|
| 35 |
+
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
| 36 |
+
|
| 37 |
+
<!-- ============================================================
|
| 38 |
+
左カラム: 入力エリア
|
| 39 |
+
============================================================ -->
|
| 40 |
+
<div class="flex flex-col gap-4">
|
| 41 |
+
|
| 42 |
+
<!-- 画像アップロード -->
|
| 43 |
+
<div>
|
| 44 |
+
<label class="block text-sm font-semibold text-gray-600 mb-2">画像アップロード</label>
|
| 45 |
+
<div id="drop-zone"
|
| 46 |
+
class="relative border-2 border-dashed border-indigo-300 rounded-xl bg-indigo-50
|
| 47 |
+
flex flex-col items-center justify-center min-h-[360px] cursor-pointer
|
| 48 |
+
transition-colors duration-200 hover:border-indigo-500 hover:bg-indigo-100">
|
| 49 |
+
|
| 50 |
+
<input type="file" id="image-input" accept="image/*" class="hidden" />
|
| 51 |
+
<img id="preview" class="hidden max-w-full max-h-80 object-contain rounded-lg shadow-sm" />
|
| 52 |
+
|
| 53 |
+
<div id="upload-placeholder" class="text-center px-6 py-8 select-none">
|
| 54 |
+
<div class="w-16 h-16 mx-auto mb-4 rounded-full bg-indigo-200 flex items-center justify-center">
|
| 55 |
+
<svg class="w-8 h-8 text-indigo-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 56 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 57 |
+
d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
|
| 58 |
+
</svg>
|
| 59 |
+
</div>
|
| 60 |
+
<p class="text-indigo-800 font-medium text-sm">クリックまたはドラッグ&ドロップ</p>
|
| 61 |
+
<p class="text-gray-400 text-xs mt-1">PNG, JPG, WEBP など</p>
|
| 62 |
+
</div>
|
| 63 |
+
|
| 64 |
+
<button id="change-btn"
|
| 65 |
+
class="hidden absolute top-3 right-3 text-xs bg-white text-indigo-800 border border-indigo-300
|
| 66 |
+
px-2 py-1 rounded-md shadow-sm hover:bg-indigo-50 transition-colors">
|
| 67 |
+
変更
|
| 68 |
+
</button>
|
| 69 |
+
</div>
|
| 70 |
+
</div>
|
| 71 |
+
|
| 72 |
+
<!-- プロンプト入力 -->
|
| 73 |
+
<div>
|
| 74 |
+
<label for="prompt-input" class="block text-sm font-semibold text-gray-600 mb-2">プロンプト</label>
|
| 75 |
+
<div class="grid grid-cols-4 gap-2 mb-2">
|
| 76 |
+
<button data-preset="text"
|
| 77 |
+
class="preset-btn text-xs font-semibold py-2 px-1 rounded-lg border transition-colors duration-150
|
| 78 |
+
bg-indigo-800 text-white border-indigo-800">
|
| 79 |
+
テキスト出力
|
| 80 |
+
</button>
|
| 81 |
+
<button data-preset="table"
|
| 82 |
+
class="preset-btn text-xs font-semibold py-2 px-1 rounded-lg border transition-colors duration-150
|
| 83 |
+
bg-white text-gray-600 border-gray-200 hover:border-indigo-400 hover:text-indigo-800">
|
| 84 |
+
テーブル出力
|
| 85 |
+
</button>
|
| 86 |
+
<button data-preset="formula"
|
| 87 |
+
class="preset-btn text-xs font-semibold py-2 px-1 rounded-lg border transition-colors duration-150
|
| 88 |
+
bg-white text-gray-600 border-gray-200 hover:border-indigo-400 hover:text-indigo-800">
|
| 89 |
+
LaTeX 出力
|
| 90 |
+
</button>
|
| 91 |
+
<button data-preset="free"
|
| 92 |
+
class="preset-btn text-xs font-semibold py-2 px-1 rounded-lg border transition-colors duration-150
|
| 93 |
+
bg-white text-gray-600 border-gray-200 hover:border-indigo-400 hover:text-indigo-800">
|
| 94 |
+
フリー入力
|
| 95 |
+
</button>
|
| 96 |
+
</div>
|
| 97 |
+
|
| 98 |
+
<textarea id="prompt-input" rows="3"
|
| 99 |
+
class="w-full border border-indigo-200 rounded-xl px-4 py-3 text-sm text-gray-700
|
| 100 |
+
focus:outline-none focus:ring-2 focus:ring-indigo-400 focus:border-transparent
|
| 101 |
+
resize-none placeholder-gray-400 transition"
|
| 102 |
+
placeholder="プロンプトを入力するか、上のボタンで選択してください。"
|
| 103 |
+
>Text Recognition:</textarea>
|
| 104 |
+
</div>
|
| 105 |
+
|
| 106 |
+
<!-- OCR 実行ボタン -->
|
| 107 |
+
<button id="submit-btn"
|
| 108 |
+
class="flex items-center justify-center gap-2 bg-violet-700 hover:bg-violet-800 active:bg-violet-900
|
| 109 |
+
text-white font-semibold py-3 px-6 rounded-xl transition-colors duration-200
|
| 110 |
+
disabled:opacity-50 disabled:cursor-not-allowed shadow-sm">
|
| 111 |
+
<svg id="btn-icon-run" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 112 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M5 3l14 9-14 9V3z" />
|
| 113 |
+
</svg>
|
| 114 |
+
<svg id="btn-icon-spin" class="hidden w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 115 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 116 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 117 |
+
</svg>
|
| 118 |
+
<span id="btn-label">OCR 実行</span>
|
| 119 |
+
</button>
|
| 120 |
+
</div>
|
| 121 |
+
|
| 122 |
+
<!-- ============================================================
|
| 123 |
+
右カラム: 結果エリア(タブ切り替え)
|
| 124 |
+
============================================================ -->
|
| 125 |
+
<div class="flex flex-col gap-0">
|
| 126 |
+
|
| 127 |
+
<!-- タブヘッダー -->
|
| 128 |
+
<div class="flex border-b border-indigo-200">
|
| 129 |
+
<button id="tab-ocr"
|
| 130 |
+
class="flex items-center gap-2 px-5 py-3 text-sm font-semibold border-b-2 border-violet-700
|
| 131 |
+
text-violet-900 bg-white transition-colors duration-150">
|
| 132 |
+
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 133 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 134 |
+
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
| 135 |
+
</svg>
|
| 136 |
+
OCR 結果
|
| 137 |
+
</button>
|
| 138 |
+
<button id="tab-translate"
|
| 139 |
+
class="flex items-center gap-2 px-5 py-3 text-sm font-semibold border-b-2 border-transparent
|
| 140 |
+
text-gray-400 bg-white transition-colors duration-150 cursor-not-allowed"
|
| 141 |
+
disabled>
|
| 142 |
+
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 143 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 144 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 145 |
+
</svg>
|
| 146 |
+
翻訳結果
|
| 147 |
+
<span id="tab-translate-badge"
|
| 148 |
+
class="hidden text-xs bg-indigo-100 text-indigo-800 rounded-full px-2 py-0.5">JP</span>
|
| 149 |
+
</button>
|
| 150 |
+
</div>
|
| 151 |
+
|
| 152 |
+
<!-- OCR タブコンテンツ -->
|
| 153 |
+
<div id="tab-content-ocr" class="flex flex-col gap-2 pt-3">
|
| 154 |
+
|
| 155 |
+
<!-- OCR ローディングパネル(処理中のみ表示) -->
|
| 156 |
+
<div id="ocr-loading-panel"
|
| 157 |
+
class="hidden items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300">
|
| 158 |
+
<svg class="w-6 h-6 shrink-0 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 159 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 160 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 161 |
+
</svg>
|
| 162 |
+
<div class="min-w-0">
|
| 163 |
+
<p id="ocr-loading-title" class="text-sm font-semibold leading-tight"></p>
|
| 164 |
+
<p id="ocr-loading-detail" class="text-xs mt-0.5 leading-tight"></p>
|
| 165 |
+
</div>
|
| 166 |
+
</div>
|
| 167 |
+
|
| 168 |
+
<div id="output-box"
|
| 169 |
+
class="result-box border border-indigo-200 rounded-xl bg-white p-5
|
| 170 |
+
min-h-[460px] max-h-[540px] overflow-y-auto
|
| 171 |
+
text-gray-800 text-sm leading-relaxed shadow-inner">
|
| 172 |
+
<div id="output-placeholder"
|
| 173 |
+
class="h-full flex flex-col items-center justify-center text-center text-gray-300 select-none">
|
| 174 |
+
<svg class="w-12 h-12 mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
|
| 175 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 176 |
+
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
| 177 |
+
</svg>
|
| 178 |
+
<p class="text-sm">OCR 結果がここに表示されます</p>
|
| 179 |
+
</div>
|
| 180 |
+
</div>
|
| 181 |
+
|
| 182 |
+
<div class="flex items-center justify-between min-h-[32px]">
|
| 183 |
+
<button id="translate-btn"
|
| 184 |
+
class="hidden flex items-center gap-1.5 bg-violet-700 hover:bg-violet-800
|
| 185 |
+
text-white text-xs font-semibold px-4 py-2 rounded-lg
|
| 186 |
+
transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm">
|
| 187 |
+
<svg id="translate-icon-run" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 188 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 189 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 190 |
+
</svg>
|
| 191 |
+
<svg id="translate-icon-spin" class="hidden w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 192 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 193 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 194 |
+
</svg>
|
| 195 |
+
<span id="translate-btn-label">日本語に翻訳</span>
|
| 196 |
+
</button>
|
| 197 |
+
|
| 198 |
+
<div class="flex items-center gap-2 ml-auto">
|
| 199 |
+
<span id="status-bar" class="text-xs text-gray-400"></span>
|
| 200 |
+
<button id="copy-btn"
|
| 201 |
+
class="hidden text-xs text-indigo-800 border border-indigo-300 bg-white
|
| 202 |
+
px-3 py-1 rounded-md hover:bg-indigo-50 transition-colors shadow-sm">
|
| 203 |
+
コピー
|
| 204 |
+
</button>
|
| 205 |
+
</div>
|
| 206 |
+
</div>
|
| 207 |
+
</div>
|
| 208 |
+
|
| 209 |
+
<!-- 翻訳タブコンテンツ -->
|
| 210 |
+
<div id="tab-content-translate" class="hidden flex flex-col gap-2 pt-3">
|
| 211 |
+
|
| 212 |
+
<!-- 翻訳ローディングパネル(処理中のみ表示) -->
|
| 213 |
+
<div id="tr-loading-panel"
|
| 214 |
+
class="hidden items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300">
|
| 215 |
+
<svg class="w-6 h-6 shrink-0 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 216 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 217 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 218 |
+
</svg>
|
| 219 |
+
<div class="min-w-0">
|
| 220 |
+
<p id="tr-loading-title" class="text-sm font-semibold leading-tight"></p>
|
| 221 |
+
<p id="tr-loading-detail" class="text-xs mt-0.5 leading-tight"></p>
|
| 222 |
+
</div>
|
| 223 |
+
</div>
|
| 224 |
+
|
| 225 |
+
<div id="translation-box"
|
| 226 |
+
class="result-box border border-indigo-200 rounded-xl bg-white p-5
|
| 227 |
+
min-h-[460px] max-h-[540px] overflow-y-auto
|
| 228 |
+
text-gray-800 text-sm leading-relaxed shadow-inner">
|
| 229 |
+
<div id="translation-placeholder"
|
| 230 |
+
class="h-full flex flex-col items-center justify-center text-center text-gray-300 select-none">
|
| 231 |
+
<svg class="w-12 h-12 mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
|
| 232 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 233 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 234 |
+
</svg>
|
| 235 |
+
<p class="text-sm">翻訳結果がここに表示されます</p>
|
| 236 |
+
</div>
|
| 237 |
+
</div>
|
| 238 |
+
|
| 239 |
+
<div class="flex items-center justify-between min-h-[32px]">
|
| 240 |
+
<button id="back-to-ocr-btn"
|
| 241 |
+
class="flex items-center gap-1 text-xs text-gray-500 hover:text-indigo-800
|
| 242 |
+
border border-gray-200 px-3 py-1.5 rounded-lg transition-colors hover:border-indigo-300">
|
| 243 |
+
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 244 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
|
| 245 |
+
</svg>
|
| 246 |
+
OCR 結果に戻る
|
| 247 |
+
</button>
|
| 248 |
+
<div class="flex items-center gap-2">
|
| 249 |
+
<span id="translate-status" class="text-xs text-gray-400"></span>
|
| 250 |
+
<button id="translate-copy-btn"
|
| 251 |
+
class="hidden text-xs text-indigo-800 border border-indigo-300 bg-white
|
| 252 |
+
px-3 py-1 rounded-md hover:bg-indigo-50 transition-colors shadow-sm">
|
| 253 |
+
コピー
|
| 254 |
+
</button>
|
| 255 |
+
</div>
|
| 256 |
+
</div>
|
| 257 |
+
</div>
|
| 258 |
+
|
| 259 |
+
</div><!-- /右カラム -->
|
| 260 |
+
</div><!-- /grid -->
|
| 261 |
+
</main>
|
| 262 |
+
|
| 263 |
+
<script>
|
| 264 |
+
// ── DOM 参照 ──────────────────────────────────────────────────
|
| 265 |
+
const dropZone = document.getElementById('drop-zone');
|
| 266 |
+
const imageInput = document.getElementById('image-input');
|
| 267 |
+
const preview = document.getElementById('preview');
|
| 268 |
+
const placeholder = document.getElementById('upload-placeholder');
|
| 269 |
+
const changeBtn = document.getElementById('change-btn');
|
| 270 |
+
const promptInput = document.getElementById('prompt-input');
|
| 271 |
+
const submitBtn = document.getElementById('submit-btn');
|
| 272 |
+
const btnLabel = document.getElementById('btn-label');
|
| 273 |
+
const btnIconRun = document.getElementById('btn-icon-run');
|
| 274 |
+
const btnIconSpin = document.getElementById('btn-icon-spin');
|
| 275 |
+
|
| 276 |
+
const outputBox = document.getElementById('output-box');
|
| 277 |
+
const outputPh = document.getElementById('output-placeholder');
|
| 278 |
+
const statusBar = document.getElementById('status-bar');
|
| 279 |
+
const copyBtn = document.getElementById('copy-btn');
|
| 280 |
+
|
| 281 |
+
const translateBtn = document.getElementById('translate-btn');
|
| 282 |
+
const translateBtnLabel = document.getElementById('translate-btn-label');
|
| 283 |
+
const translateIconRun = document.getElementById('translate-icon-run');
|
| 284 |
+
const translateIconSpin = document.getElementById('translate-icon-spin');
|
| 285 |
+
|
| 286 |
+
const translationBox = document.getElementById('translation-box');
|
| 287 |
+
const translationPh = document.getElementById('translation-placeholder');
|
| 288 |
+
const translateStatus = document.getElementById('translate-status');
|
| 289 |
+
const translateCopyBtn = document.getElementById('translate-copy-btn');
|
| 290 |
+
const backToOcrBtn = document.getElementById('back-to-ocr-btn');
|
| 291 |
+
|
| 292 |
+
const tabOcr = document.getElementById('tab-ocr');
|
| 293 |
+
const tabTranslate = document.getElementById('tab-translate');
|
| 294 |
+
const tabTranslateBadge = document.getElementById('tab-translate-badge');
|
| 295 |
+
const tabContentOcr = document.getElementById('tab-content-ocr');
|
| 296 |
+
const tabContentTr = document.getElementById('tab-content-translate');
|
| 297 |
+
|
| 298 |
+
const ocrLoadingPanel = document.getElementById('ocr-loading-panel');
|
| 299 |
+
const ocrLoadingTitle = document.getElementById('ocr-loading-title');
|
| 300 |
+
const ocrLoadingDetail = document.getElementById('ocr-loading-detail');
|
| 301 |
+
const trLoadingPanel = document.getElementById('tr-loading-panel');
|
| 302 |
+
const trLoadingTitle = document.getElementById('tr-loading-title');
|
| 303 |
+
const trLoadingDetail = document.getElementById('tr-loading-detail');
|
| 304 |
+
|
| 305 |
+
// ── ローディングパネル表示制御 ─────────────────────────────────
|
| 306 |
+
function showPanel(panel, titleEl, detailEl, type, message, detail) {
|
| 307 |
+
const isLoading = type === 'loading';
|
| 308 |
+
const colorText = isLoading ? 'text-amber-700' : 'text-indigo-700';
|
| 309 |
+
const colorDetail = isLoading ? 'text-amber-500' : 'text-indigo-400';
|
| 310 |
+
const colorBorder = isLoading ? 'border-amber-200 bg-amber-50' : 'border-indigo-200 bg-indigo-50';
|
| 311 |
+
const colorSpin = isLoading ? 'text-amber-500' : 'text-indigo-500';
|
| 312 |
+
// クラスリセット
|
| 313 |
+
panel.className = `flex items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300 ${colorBorder}`;
|
| 314 |
+
titleEl.className = `text-sm font-semibold leading-tight ${colorText}`;
|
| 315 |
+
detailEl.className = `text-xs mt-0.5 leading-tight ${colorDetail}`;
|
| 316 |
+
// スピナーの色
|
| 317 |
+
panel.querySelector('svg').className = `w-6 h-6 shrink-0 animate-spin ${colorSpin}`;
|
| 318 |
+
titleEl.textContent = message;
|
| 319 |
+
detailEl.textContent = detail || '';
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
function hidePanel(panel) {
|
| 323 |
+
panel.className = 'hidden items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300';
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
// ── タブ切り替え ────────────────────────────────────────────────
|
| 327 |
+
function switchTab(name) {
|
| 328 |
+
const isOcr = name === 'ocr';
|
| 329 |
+
tabOcr.classList.toggle('border-violet-700', isOcr);
|
| 330 |
+
tabOcr.classList.toggle('text-violet-900', isOcr);
|
| 331 |
+
tabOcr.classList.toggle('border-transparent', !isOcr);
|
| 332 |
+
tabOcr.classList.toggle('text-gray-400', !isOcr);
|
| 333 |
+
tabTranslate.classList.toggle('border-violet-700', !isOcr);
|
| 334 |
+
tabTranslate.classList.toggle('text-violet-900', !isOcr);
|
| 335 |
+
tabTranslate.classList.toggle('border-transparent', isOcr);
|
| 336 |
+
tabContentOcr.classList.toggle('hidden', !isOcr);
|
| 337 |
+
tabContentTr.classList.toggle('hidden', isOcr);
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
tabOcr.addEventListener('click', () => switchTab('ocr'));
|
| 341 |
+
tabTranslate.addEventListener('click', () => {
|
| 342 |
+
if (!tabTranslate.disabled) switchTab('translate');
|
| 343 |
+
});
|
| 344 |
+
backToOcrBtn.addEventListener('click', () => switchTab('ocr'));
|
| 345 |
+
|
| 346 |
+
// ── 画像アップロード ───────────────────────────────────────────
|
| 347 |
+
dropZone.addEventListener('click', (e) => {
|
| 348 |
+
if (e.target === changeBtn) return;
|
| 349 |
+
imageInput.click();
|
| 350 |
+
});
|
| 351 |
+
changeBtn.addEventListener('click', (e) => {
|
| 352 |
+
e.stopPropagation();
|
| 353 |
+
imageInput.click();
|
| 354 |
+
});
|
| 355 |
+
imageInput.addEventListener('change', (e) => {
|
| 356 |
+
const file = e.target.files[0];
|
| 357 |
+
if (file) showPreview(file);
|
| 358 |
+
});
|
| 359 |
+
dropZone.addEventListener('dragover', (e) => {
|
| 360 |
+
e.preventDefault();
|
| 361 |
+
dropZone.classList.add('drag-over');
|
| 362 |
+
});
|
| 363 |
+
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
|
| 364 |
+
dropZone.addEventListener('drop', (e) => {
|
| 365 |
+
e.preventDefault();
|
| 366 |
+
dropZone.classList.remove('drag-over');
|
| 367 |
+
const file = e.dataTransfer.files[0];
|
| 368 |
+
if (file && file.type.startsWith('image/')) {
|
| 369 |
+
showPreview(file);
|
| 370 |
+
const dt = new DataTransfer();
|
| 371 |
+
dt.items.add(file);
|
| 372 |
+
imageInput.files = dt.files;
|
| 373 |
+
}
|
| 374 |
+
});
|
| 375 |
+
|
| 376 |
+
function showPreview(file) {
|
| 377 |
+
const reader = new FileReader();
|
| 378 |
+
reader.onload = (e) => {
|
| 379 |
+
preview.src = e.target.result;
|
| 380 |
+
preview.classList.remove('hidden');
|
| 381 |
+
placeholder.classList.add('hidden');
|
| 382 |
+
changeBtn.classList.remove('hidden');
|
| 383 |
+
};
|
| 384 |
+
reader.readAsDataURL(file);
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
// ── SSE 共通パーサー ────────────────────────────────────────────
|
| 388 |
+
async function consumeSSE(response, onData) {
|
| 389 |
+
const reader = response.body.getReader();
|
| 390 |
+
const decoder = new TextDecoder();
|
| 391 |
+
let buffer = '';
|
| 392 |
+
while (true) {
|
| 393 |
+
const { done, value } = await reader.read();
|
| 394 |
+
if (done) break;
|
| 395 |
+
buffer += decoder.decode(value, { stream: true });
|
| 396 |
+
const lines = buffer.split('\n');
|
| 397 |
+
buffer = lines.pop();
|
| 398 |
+
for (const line of lines) {
|
| 399 |
+
if (!line.startsWith('data: ')) continue;
|
| 400 |
+
try { onData(JSON.parse(line.slice(6))); } catch { /* ignore */ }
|
| 401 |
+
}
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
// ── OCR 実行 ──────────────────────────────────────────────────
|
| 406 |
+
submitBtn.addEventListener('click', async () => {
|
| 407 |
+
const file = imageInput.files[0];
|
| 408 |
+
if (!file) { alert('画像をアップロードしてください。'); return; }
|
| 409 |
+
|
| 410 |
+
setOcrLoading(true);
|
| 411 |
+
outputBox.innerHTML = '';
|
| 412 |
+
outputPh.classList.add('hidden');
|
| 413 |
+
copyBtn.classList.add('hidden');
|
| 414 |
+
translateBtn.classList.add('hidden');
|
| 415 |
+
hidePanel(ocrLoadingPanel);
|
| 416 |
+
setStatus('');
|
| 417 |
+
|
| 418 |
+
tabTranslate.disabled = true;
|
| 419 |
+
tabTranslate.classList.add('cursor-not-allowed');
|
| 420 |
+
tabTranslate.classList.remove('hover:text-violet-900', 'cursor-pointer');
|
| 421 |
+
tabTranslateBadge.classList.add('hidden');
|
| 422 |
+
translationBox.innerHTML = '';
|
| 423 |
+
translationPh.classList.remove('hidden');
|
| 424 |
+
translateCopyBtn.classList.add('hidden');
|
| 425 |
+
translateStatus.textContent = '';
|
| 426 |
+
switchTab('ocr');
|
| 427 |
+
|
| 428 |
+
const formData = new FormData();
|
| 429 |
+
formData.append('image', file);
|
| 430 |
+
formData.append('prompt', promptInput.value);
|
| 431 |
+
|
| 432 |
+
try {
|
| 433 |
+
const response = await fetch('/ocr/run', { method: 'POST', body: formData });
|
| 434 |
+
if (!response.ok) throw new Error(`HTTP エラー: ${response.status}`);
|
| 435 |
+
|
| 436 |
+
await consumeSSE(response, (data) => {
|
| 437 |
+
if (data.status) {
|
| 438 |
+
showPanel(ocrLoadingPanel, ocrLoadingTitle, ocrLoadingDetail,
|
| 439 |
+
data.status, data.message, data.detail);
|
| 440 |
+
}
|
| 441 |
+
if (data.text !== undefined) {
|
| 442 |
+
hidePanel(ocrLoadingPanel);
|
| 443 |
+
outputBox.innerHTML = data.text;
|
| 444 |
+
outputBox.scrollTop = outputBox.scrollHeight;
|
| 445 |
+
}
|
| 446 |
+
if (data.done) {
|
| 447 |
+
hidePanel(ocrLoadingPanel);
|
| 448 |
+
setStatus('完了');
|
| 449 |
+
copyBtn.classList.remove('hidden');
|
| 450 |
+
translateBtn.classList.remove('hidden');
|
| 451 |
+
tabTranslate.disabled = false;
|
| 452 |
+
tabTranslate.classList.remove('cursor-not-allowed', 'text-gray-400');
|
| 453 |
+
tabTranslate.classList.add('hover:text-violet-900', 'cursor-pointer', 'text-gray-500');
|
| 454 |
+
}
|
| 455 |
+
if (data.error) {
|
| 456 |
+
hidePanel(ocrLoadingPanel);
|
| 457 |
+
outputBox.innerHTML = `<p class="text-red-500 font-medium">${data.error}</p>`;
|
| 458 |
+
setStatus('エラー');
|
| 459 |
+
}
|
| 460 |
+
});
|
| 461 |
+
} catch (err) {
|
| 462 |
+
outputBox.innerHTML = `<p class="text-red-500 font-medium">エラーが発生しました: ${err.message}</p>`;
|
| 463 |
+
setStatus('エラー');
|
| 464 |
+
} finally {
|
| 465 |
+
setOcrLoading(false);
|
| 466 |
+
}
|
| 467 |
+
});
|
| 468 |
+
|
| 469 |
+
// ── 翻訳実行 ──────────────────────────────────────────────────
|
| 470 |
+
translateBtn.addEventListener('click', async () => {
|
| 471 |
+
const ocrText = outputBox.innerText.trim();
|
| 472 |
+
if (!ocrText) { alert('翻訳するテキストがありません。'); return; }
|
| 473 |
+
|
| 474 |
+
switchTab('translate');
|
| 475 |
+
setTranslateLoading(true);
|
| 476 |
+
translationBox.innerHTML = '';
|
| 477 |
+
translationPh.classList.add('hidden');
|
| 478 |
+
translateCopyBtn.classList.add('hidden');
|
| 479 |
+
translateStatus.textContent = '';
|
| 480 |
+
tabTranslateBadge.classList.add('hidden');
|
| 481 |
+
hidePanel(trLoadingPanel);
|
| 482 |
+
|
| 483 |
+
const formData = new FormData();
|
| 484 |
+
formData.append('text', ocrText);
|
| 485 |
+
|
| 486 |
+
try {
|
| 487 |
+
const response = await fetch('/ocr/translate', { method: 'POST', body: formData });
|
| 488 |
+
if (!response.ok) throw new Error(`HTTP エラー: ${response.status}`);
|
| 489 |
+
|
| 490 |
+
await consumeSSE(response, (data) => {
|
| 491 |
+
if (data.status) {
|
| 492 |
+
showPanel(trLoadingPanel, trLoadingTitle, trLoadingDetail,
|
| 493 |
+
data.status, data.message, data.detail);
|
| 494 |
+
}
|
| 495 |
+
if (data.text !== undefined) {
|
| 496 |
+
hidePanel(trLoadingPanel);
|
| 497 |
+
translationBox.innerHTML = data.text;
|
| 498 |
+
translationBox.scrollTop = translationBox.scrollHeight;
|
| 499 |
+
}
|
| 500 |
+
if (data.done) {
|
| 501 |
+
hidePanel(trLoadingPanel);
|
| 502 |
+
translateStatus.textContent = '翻訳完了';
|
| 503 |
+
translateCopyBtn.classList.remove('hidden');
|
| 504 |
+
tabTranslateBadge.classList.remove('hidden');
|
| 505 |
+
}
|
| 506 |
+
if (data.error) {
|
| 507 |
+
hidePanel(trLoadingPanel);
|
| 508 |
+
translationBox.innerHTML = `<p class="text-red-500 font-medium">${data.error}</p>`;
|
| 509 |
+
translateStatus.textContent = 'エラー';
|
| 510 |
+
}
|
| 511 |
+
});
|
| 512 |
+
} catch (err) {
|
| 513 |
+
translationBox.innerHTML = `<p class="text-red-500 font-medium">エラー: ${err.message}</p>`;
|
| 514 |
+
translateStatus.textContent = 'エラー';
|
| 515 |
+
} finally {
|
| 516 |
+
setTranslateLoading(false);
|
| 517 |
+
}
|
| 518 |
+
});
|
| 519 |
+
|
| 520 |
+
// ── プリセットボタン ───────────────────────────────────────────
|
| 521 |
+
const PRESETS = {
|
| 522 |
+
text: 'Text Recognition:',
|
| 523 |
+
table: 'Table Recognition:',
|
| 524 |
+
formula: 'Formula Recognition:',
|
| 525 |
+
free: '',
|
| 526 |
+
};
|
| 527 |
+
const ACTIVE = ['bg-indigo-800', 'text-white', 'border-indigo-800'];
|
| 528 |
+
const INACTIVE = ['bg-white', 'text-gray-600', 'border-gray-200',
|
| 529 |
+
'hover:border-indigo-400', 'hover:text-indigo-800'];
|
| 530 |
+
|
| 531 |
+
document.querySelectorAll('.preset-btn').forEach((btn) => {
|
| 532 |
+
btn.addEventListener('click', () => {
|
| 533 |
+
const preset = btn.dataset.preset;
|
| 534 |
+
promptInput.value = PRESETS[preset];
|
| 535 |
+
if (preset === 'free') promptInput.focus();
|
| 536 |
+
document.querySelectorAll('.preset-btn').forEach((b) => {
|
| 537 |
+
b.classList.remove(...ACTIVE);
|
| 538 |
+
b.classList.add(...INACTIVE);
|
| 539 |
+
});
|
| 540 |
+
btn.classList.add(...ACTIVE);
|
| 541 |
+
btn.classList.remove(...INACTIVE);
|
| 542 |
+
});
|
| 543 |
+
});
|
| 544 |
+
|
| 545 |
+
promptInput.addEventListener('input', () => {
|
| 546 |
+
const val = promptInput.value;
|
| 547 |
+
const matched = Object.entries(PRESETS).find(([k, v]) => k !== 'free' && v === val);
|
| 548 |
+
if (!matched) {
|
| 549 |
+
document.querySelectorAll('.preset-btn').forEach((b) => {
|
| 550 |
+
b.classList.remove(...ACTIVE);
|
| 551 |
+
b.classList.add(...INACTIVE);
|
| 552 |
+
});
|
| 553 |
+
document.querySelector('[data-preset="free"]').classList.add(...ACTIVE);
|
| 554 |
+
document.querySelector('[data-preset="free"]').classList.remove(...INACTIVE);
|
| 555 |
+
}
|
| 556 |
+
});
|
| 557 |
+
|
| 558 |
+
// ── コピーボタン ────────────────────────────────────────────────
|
| 559 |
+
function setupCopy(btn, srcEl) {
|
| 560 |
+
btn.addEventListener('click', () => {
|
| 561 |
+
navigator.clipboard.writeText(srcEl.innerText).then(() => {
|
| 562 |
+
const orig = btn.textContent;
|
| 563 |
+
btn.textContent = 'コピーしました!';
|
| 564 |
+
setTimeout(() => { btn.textContent = orig; }, 2000);
|
| 565 |
+
});
|
| 566 |
+
});
|
| 567 |
+
}
|
| 568 |
+
setupCopy(copyBtn, outputBox);
|
| 569 |
+
setupCopy(translateCopyBtn, translationBox);
|
| 570 |
+
|
| 571 |
+
// ── UI 状態管理 ──────────────────────────────────────────────────
|
| 572 |
+
function setOcrLoading(loading) {
|
| 573 |
+
submitBtn.disabled = loading;
|
| 574 |
+
btnLabel.textContent = loading ? '処理中...' : 'OCR 実行';
|
| 575 |
+
btnIconRun.classList.toggle('hidden', loading);
|
| 576 |
+
btnIconSpin.classList.toggle('hidden', !loading);
|
| 577 |
+
}
|
| 578 |
+
function setTranslateLoading(loading) {
|
| 579 |
+
translateBtn.disabled = loading;
|
| 580 |
+
translateBtnLabel.textContent = loading ? '翻訳中...' : '日本語に翻訳';
|
| 581 |
+
translateIconRun.classList.toggle('hidden', loading);
|
| 582 |
+
translateIconSpin.classList.toggle('hidden', !loading);
|
| 583 |
+
}
|
| 584 |
+
function setStatus(text) { statusBar.textContent = text; }
|
| 585 |
+
</script>
|
| 586 |
+
{% endblock %}
|
MM_tools/app/blueprints/translation/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint
|
| 2 |
+
|
| 3 |
+
translation_bp = Blueprint(
|
| 4 |
+
"translation",
|
| 5 |
+
__name__,
|
| 6 |
+
template_folder="templates",
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
from . import routes # noqa: E402, F401
|
MM_tools/app/blueprints/translation/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (358 Bytes). View file
|
|
|
MM_tools/app/blueprints/translation/__pycache__/routes.cpython-314.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
MM_tools/app/blueprints/translation/routes.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
translation ブループリント ルーティング。
|
| 3 |
+
|
| 4 |
+
① 多言語翻訳ページ。
|
| 5 |
+
テキストを受け取り、指定言語へ LFM 2.5 (ONNX) で翻訳する。
|
| 6 |
+
翻訳結果は SSE (Server-Sent Events) でストリーミング送信する。
|
| 7 |
+
ステータスイベント: {"status": "loading"|"processing", "message": "...", "detail": "..."}
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from flask import render_template, request, Response, stream_with_context
|
| 11 |
+
from . import translation_bp
|
| 12 |
+
from app.shared.models import get_lfm, is_lfm_loaded, get_lfm_lock
|
| 13 |
+
from app.shared.utils import sse_event
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@translation_bp.route("/")
|
| 17 |
+
def index():
|
| 18 |
+
"""翻訳ページを返す。"""
|
| 19 |
+
return render_template("translation/index.html")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@translation_bp.route("/translate", methods=["POST"])
|
| 23 |
+
def translate():
|
| 24 |
+
"""
|
| 25 |
+
テキストを受け取り、指定言語に翻訳して SSE でストリーミングする。
|
| 26 |
+
|
| 27 |
+
Form data:
|
| 28 |
+
text (str) : 翻訳対象テキスト
|
| 29 |
+
source_lang (str): 原文言語(例: "Auto", "日本語", "English")
|
| 30 |
+
target_lang (str): 翻訳先言語(例: "日本語", "English", "中国語")
|
| 31 |
+
|
| 32 |
+
SSE イベント:
|
| 33 |
+
{"status": "loading", "message": "...", "detail": "..."}
|
| 34 |
+
{"status": "processing", "message": "...", "detail": "..."}
|
| 35 |
+
{"text": "累積テキスト"}
|
| 36 |
+
{"done": True}
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
text/event-stream
|
| 40 |
+
"""
|
| 41 |
+
text = request.form.get("text", "").strip()
|
| 42 |
+
source_lang = request.form.get("source_lang", "Auto").strip() or "Auto"
|
| 43 |
+
target_lang = request.form.get("target_lang", "日本語").strip() or "日本語"
|
| 44 |
+
|
| 45 |
+
if not text:
|
| 46 |
+
def _err():
|
| 47 |
+
yield sse_event({"error": "翻訳するテキストを入力してください。"})
|
| 48 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 49 |
+
|
| 50 |
+
# 原文言語の付加情報をユーザープロンプトに含める
|
| 51 |
+
if source_lang.lower() in ("auto", "自動"):
|
| 52 |
+
user_prompt = text
|
| 53 |
+
else:
|
| 54 |
+
user_prompt = f"({source_lang})\n{text}"
|
| 55 |
+
|
| 56 |
+
system_prompt = (
|
| 57 |
+
f"あなたはプロの翻訳者です。"
|
| 58 |
+
f"与えられた文章を{target_lang}に翻訳してください。"
|
| 59 |
+
"翻訳文のみを出力してください。説明や補足は不要です。"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def generate():
|
| 63 |
+
"""翻訳トークンを SSE で送信するジェネレータ。"""
|
| 64 |
+
with get_lfm_lock():
|
| 65 |
+
# モデルロード状態を通知
|
| 66 |
+
if not is_lfm_loaded():
|
| 67 |
+
yield sse_event({
|
| 68 |
+
"status": "loading",
|
| 69 |
+
"message": "翻訳モデルをロード中...",
|
| 70 |
+
"detail": "初回のみ数分かかります。しばらくお待ちください。",
|
| 71 |
+
})
|
| 72 |
+
else:
|
| 73 |
+
yield sse_event({
|
| 74 |
+
"status": "processing",
|
| 75 |
+
"message": "翻訳中...",
|
| 76 |
+
"detail": f"{target_lang} に変換しています",
|
| 77 |
+
})
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
llm = get_lfm()
|
| 81 |
+
yield sse_event({
|
| 82 |
+
"status": "processing",
|
| 83 |
+
"message": "翻訳中...",
|
| 84 |
+
"detail": f"{target_lang} に変換しています",
|
| 85 |
+
})
|
| 86 |
+
for chunk in llm.stream(user_prompt=user_prompt, system_prompt=system_prompt):
|
| 87 |
+
yield sse_event({"text": chunk})
|
| 88 |
+
yield sse_event({"done": True})
|
| 89 |
+
except Exception as exc:
|
| 90 |
+
yield sse_event({"error": f"翻訳エラー: {exc}"})
|
| 91 |
+
|
| 92 |
+
response = Response(
|
| 93 |
+
stream_with_context(generate()),
|
| 94 |
+
mimetype="text/event-stream",
|
| 95 |
+
)
|
| 96 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 97 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 98 |
+
return response
|
MM_tools/app/blueprints/translation/templates/translation/index.html
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}多言語翻訳 - AI Tools{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block head %}
|
| 6 |
+
<style>
|
| 7 |
+
.lang-select option { background: white; }
|
| 8 |
+
textarea::-webkit-scrollbar { width: 6px; }
|
| 9 |
+
textarea::-webkit-scrollbar-track { background: #f1f5f9; }
|
| 10 |
+
textarea::-webkit-scrollbar-thumb { background: #a5b4fc; border-radius: 3px; }
|
| 11 |
+
#output-area::-webkit-scrollbar { width: 6px; }
|
| 12 |
+
#output-area::-webkit-scrollbar-track { background: #f1f5f9; }
|
| 13 |
+
#output-area::-webkit-scrollbar-thumb { background: #a5b4fc; border-radius: 3px; }
|
| 14 |
+
</style>
|
| 15 |
+
{% endblock %}
|
| 16 |
+
|
| 17 |
+
{% block content %}
|
| 18 |
+
<main class="max-w-7xl mx-auto px-6 py-8">
|
| 19 |
+
|
| 20 |
+
<!-- ページタイトル -->
|
| 21 |
+
<div class="flex items-center gap-3 mb-6">
|
| 22 |
+
<div class="w-9 h-9 rounded-lg bg-indigo-700 flex items-center justify-center">
|
| 23 |
+
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 24 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 25 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 26 |
+
</svg>
|
| 27 |
+
</div>
|
| 28 |
+
<div>
|
| 29 |
+
<h1 class="text-2xl font-bold text-gray-900">多言語翻訳</h1>
|
| 30 |
+
<p class="text-sm text-gray-400">LFM 2.5 (ONNX) によるローカル翻訳</p>
|
| 31 |
+
</div>
|
| 32 |
+
</div>
|
| 33 |
+
|
| 34 |
+
<!-- 翻訳エリア(左右2カラム) -->
|
| 35 |
+
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
| 36 |
+
|
| 37 |
+
<!-- ===== 左カラム: 入力 ===== -->
|
| 38 |
+
<div class="flex flex-col gap-3">
|
| 39 |
+
|
| 40 |
+
<!-- 原文言語セレクタ -->
|
| 41 |
+
<div class="flex items-center gap-2">
|
| 42 |
+
<label class="text-xs font-semibold text-gray-500 shrink-0">原文言語:</label>
|
| 43 |
+
<select id="source-lang-select"
|
| 44 |
+
class="lang-select text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white
|
| 45 |
+
focus:outline-none focus:ring-2 focus:ring-indigo-400">
|
| 46 |
+
<option value="Auto" selected>Auto(自動検出)</option>
|
| 47 |
+
<option value="日本語">日本語</option>
|
| 48 |
+
<option value="English">English</option>
|
| 49 |
+
<option value="中国語">中国語</option>
|
| 50 |
+
<option value="韓国語">韓国語</option>
|
| 51 |
+
<option value="フランス語">フランス語</option>
|
| 52 |
+
<option value="ドイツ語">ドイツ語</option>
|
| 53 |
+
<option value="スペイン語">スペイン語</option>
|
| 54 |
+
<option value="custom">その他(自由入力)</option>
|
| 55 |
+
</select>
|
| 56 |
+
<input id="source-lang-custom" type="text" placeholder="言語を入力..."
|
| 57 |
+
class="hidden text-sm border border-indigo-300 rounded-lg px-3 py-1.5 w-36
|
| 58 |
+
focus:outline-none focus:ring-2 focus:ring-indigo-400" />
|
| 59 |
+
</div>
|
| 60 |
+
|
| 61 |
+
<!-- 入力テキストエリア -->
|
| 62 |
+
<textarea id="input-text" rows="14"
|
| 63 |
+
class="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm text-gray-800
|
| 64 |
+
focus:outline-none focus:ring-2 focus:ring-indigo-400 focus:border-transparent
|
| 65 |
+
resize-none placeholder-gray-300 transition shadow-sm"
|
| 66 |
+
placeholder="翻訳したいテキストをここに入力してください..."></textarea>
|
| 67 |
+
|
| 68 |
+
<!-- 文字数カウント -->
|
| 69 |
+
<div class="flex items-center justify-between text-xs text-gray-400">
|
| 70 |
+
<span id="char-count">0 文字</span>
|
| 71 |
+
<button id="clear-btn"
|
| 72 |
+
class="text-xs text-gray-400 hover:text-red-500 transition-colors border border-gray-200
|
| 73 |
+
hover:border-red-300 px-2 py-1 rounded-md">
|
| 74 |
+
クリア
|
| 75 |
+
</button>
|
| 76 |
+
</div>
|
| 77 |
+
|
| 78 |
+
<!-- 実行ボタン + オプション -->
|
| 79 |
+
<div class="flex items-center gap-3">
|
| 80 |
+
<button id="translate-btn"
|
| 81 |
+
class="flex items-center justify-center gap-2 bg-indigo-700 hover:bg-indigo-800 active:bg-indigo-900
|
| 82 |
+
text-white font-semibold py-3 px-8 rounded-xl transition-colors duration-200
|
| 83 |
+
disabled:opacity-50 disabled:cursor-not-allowed shadow-sm flex-1">
|
| 84 |
+
<svg id="btn-icon-run" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 85 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 86 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 87 |
+
</svg>
|
| 88 |
+
<svg id="btn-icon-spin" class="hidden w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 89 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 90 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 91 |
+
</svg>
|
| 92 |
+
<span id="btn-label">翻訳を実行</span>
|
| 93 |
+
</button>
|
| 94 |
+
|
| 95 |
+
<!-- オプション: テキスト貼り付け -->
|
| 96 |
+
<button id="paste-btn"
|
| 97 |
+
class="text-sm text-gray-500 hover:text-indigo-700 border border-gray-200
|
| 98 |
+
hover:border-indigo-300 px-3 py-2.5 rounded-xl transition-colors">
|
| 99 |
+
貼り付け
|
| 100 |
+
</button>
|
| 101 |
+
</div>
|
| 102 |
+
|
| 103 |
+
<!-- ショートカットヒント -->
|
| 104 |
+
<p class="text-xs text-gray-300 text-center">
|
| 105 |
+
Ctrl + Enter でも翻訳できます
|
| 106 |
+
</p>
|
| 107 |
+
</div>
|
| 108 |
+
|
| 109 |
+
<!-- ===== 右カラム: 出力 ===== -->
|
| 110 |
+
<div class="flex flex-col gap-3">
|
| 111 |
+
|
| 112 |
+
<!-- 翻訳先言語セレクタ -->
|
| 113 |
+
<div class="flex items-center gap-2">
|
| 114 |
+
<label class="text-xs font-semibold text-gray-500 shrink-0">翻訳先:</label>
|
| 115 |
+
<select id="target-lang-select"
|
| 116 |
+
class="lang-select text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white
|
| 117 |
+
focus:outline-none focus:ring-2 focus:ring-indigo-400">
|
| 118 |
+
<option value="日本語" selected>日本語</option>
|
| 119 |
+
<option value="English">English</option>
|
| 120 |
+
<option value="中国語">中国語</option>
|
| 121 |
+
<option value="韓国語">韓国語</option>
|
| 122 |
+
<option value="フランス語">フランス語</option>
|
| 123 |
+
<option value="ドイツ語">ドイツ語</option>
|
| 124 |
+
<option value="スペイン語">スペイン語</option>
|
| 125 |
+
<option value="custom">その他(自由入力)</option>
|
| 126 |
+
</select>
|
| 127 |
+
<input id="target-lang-custom" type="text" placeholder="言語を入力..."
|
| 128 |
+
class="hidden text-sm border border-indigo-300 rounded-lg px-3 py-1.5 w-36
|
| 129 |
+
focus:outline-none focus:ring-2 focus:ring-indigo-400" />
|
| 130 |
+
</div>
|
| 131 |
+
|
| 132 |
+
<!-- ローディングパネル(処理中のみ表示) -->
|
| 133 |
+
<div id="loading-panel"
|
| 134 |
+
class="hidden items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300">
|
| 135 |
+
<svg class="w-6 h-6 shrink-0 animate-spin" viewBox="0 0 24 24" fill="none">
|
| 136 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
|
| 137 |
+
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
|
| 138 |
+
</svg>
|
| 139 |
+
<div class="min-w-0">
|
| 140 |
+
<p id="loading-title" class="text-sm font-semibold leading-tight"></p>
|
| 141 |
+
<p id="loading-detail" class="text-xs mt-0.5 leading-tight"></p>
|
| 142 |
+
</div>
|
| 143 |
+
</div>
|
| 144 |
+
|
| 145 |
+
<!-- 出力エリア -->
|
| 146 |
+
<div id="output-area"
|
| 147 |
+
class="flex-1 border border-gray-200 rounded-xl bg-white px-4 py-3
|
| 148 |
+
min-h-[336px] max-h-[400px] overflow-y-auto text-sm text-gray-800
|
| 149 |
+
leading-relaxed shadow-sm">
|
| 150 |
+
<div id="output-placeholder"
|
| 151 |
+
class="h-full flex flex-col items-center justify-center text-center text-gray-300 select-none py-16">
|
| 152 |
+
<svg class="w-12 h-12 mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
|
| 153 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 154 |
+
d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
|
| 155 |
+
</svg>
|
| 156 |
+
<p class="text-sm">翻訳結果がここに表示されます</p>
|
| 157 |
+
</div>
|
| 158 |
+
</div>
|
| 159 |
+
|
| 160 |
+
<!-- 出力アクションバー -->
|
| 161 |
+
<div class="flex items-center justify-between min-h-[32px]">
|
| 162 |
+
<span id="status-bar" class="text-xs text-gray-400"></span>
|
| 163 |
+
<div class="flex items-center gap-2">
|
| 164 |
+
<span id="output-char-count" class="text-xs text-gray-300"></span>
|
| 165 |
+
<button id="copy-btn"
|
| 166 |
+
class="hidden text-xs text-indigo-700 border border-indigo-200 bg-white
|
| 167 |
+
px-3 py-1 rounded-md hover:bg-indigo-50 transition-colors shadow-sm">
|
| 168 |
+
コピー
|
| 169 |
+
</button>
|
| 170 |
+
</div>
|
| 171 |
+
</div>
|
| 172 |
+
</div>
|
| 173 |
+
|
| 174 |
+
</div><!-- /grid -->
|
| 175 |
+
</main>
|
| 176 |
+
|
| 177 |
+
<script>
|
| 178 |
+
// ── DOM 参照 ────────────────────────────────────────────────────
|
| 179 |
+
const inputText = document.getElementById('input-text');
|
| 180 |
+
const charCount = document.getElementById('char-count');
|
| 181 |
+
const outputArea = document.getElementById('output-area');
|
| 182 |
+
const outputPh = document.getElementById('output-placeholder');
|
| 183 |
+
const statusBar = document.getElementById('status-bar');
|
| 184 |
+
const copyBtn = document.getElementById('copy-btn');
|
| 185 |
+
const outputCharCount = document.getElementById('output-char-count');
|
| 186 |
+
const translateBtn = document.getElementById('translate-btn');
|
| 187 |
+
const btnLabel = document.getElementById('btn-label');
|
| 188 |
+
const btnIconRun = document.getElementById('btn-icon-run');
|
| 189 |
+
const btnIconSpin = document.getElementById('btn-icon-spin');
|
| 190 |
+
const clearBtn = document.getElementById('clear-btn');
|
| 191 |
+
const pasteBtn = document.getElementById('paste-btn');
|
| 192 |
+
|
| 193 |
+
const sourceLangSelect = document.getElementById('source-lang-select');
|
| 194 |
+
const sourceLangCustom = document.getElementById('source-lang-custom');
|
| 195 |
+
const targetLangSelect = document.getElementById('target-lang-select');
|
| 196 |
+
const targetLangCustom = document.getElementById('target-lang-custom');
|
| 197 |
+
|
| 198 |
+
const loadingPanel = document.getElementById('loading-panel');
|
| 199 |
+
const loadingTitle = document.getElementById('loading-title');
|
| 200 |
+
const loadingDetail = document.getElementById('loading-detail');
|
| 201 |
+
|
| 202 |
+
// ── ローディングパネル表示制御 ─────────────────────────────────
|
| 203 |
+
function showPanel(type, message, detail) {
|
| 204 |
+
const isLoading = type === 'loading';
|
| 205 |
+
const colorBorder = isLoading ? 'border-amber-200 bg-amber-50' : 'border-indigo-200 bg-indigo-50';
|
| 206 |
+
const colorText = isLoading ? 'text-amber-700' : 'text-indigo-700';
|
| 207 |
+
const colorDetail = isLoading ? 'text-amber-500' : 'text-indigo-400';
|
| 208 |
+
const colorSpin = isLoading ? 'text-amber-500' : 'text-indigo-500';
|
| 209 |
+
loadingPanel.className = `flex items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300 ${colorBorder}`;
|
| 210 |
+
loadingPanel.querySelector('svg').className = `w-6 h-6 shrink-0 animate-spin ${colorSpin}`;
|
| 211 |
+
loadingTitle.className = `text-sm font-semibold leading-tight ${colorText}`;
|
| 212 |
+
loadingDetail.className = `text-xs mt-0.5 leading-tight ${colorDetail}`;
|
| 213 |
+
loadingTitle.textContent = message;
|
| 214 |
+
loadingDetail.textContent = detail || '';
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
function hidePanel() {
|
| 218 |
+
loadingPanel.className = 'hidden items-center gap-3 px-4 py-3 rounded-xl border transition-all duration-300';
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
// ── 文字数カウント ──────────────────────────────────────────────
|
| 222 |
+
inputText.addEventListener('input', () => {
|
| 223 |
+
charCount.textContent = `${inputText.value.length.toLocaleString()} 文字`;
|
| 224 |
+
});
|
| 225 |
+
|
| 226 |
+
// ── 言語セレクタ(自由入力切り替え) ──────────────────────────
|
| 227 |
+
function handleLangSelect(select, customInput) {
|
| 228 |
+
select.addEventListener('change', () => {
|
| 229 |
+
if (select.value === 'custom') {
|
| 230 |
+
customInput.classList.remove('hidden');
|
| 231 |
+
customInput.focus();
|
| 232 |
+
} else {
|
| 233 |
+
customInput.classList.add('hidden');
|
| 234 |
+
}
|
| 235 |
+
});
|
| 236 |
+
}
|
| 237 |
+
handleLangSelect(sourceLangSelect, sourceLangCustom);
|
| 238 |
+
handleLangSelect(targetLangSelect, targetLangCustom);
|
| 239 |
+
|
| 240 |
+
function getSourceLang() {
|
| 241 |
+
return sourceLangSelect.value === 'custom' ? sourceLangCustom.value.trim() || 'Auto' : sourceLangSelect.value;
|
| 242 |
+
}
|
| 243 |
+
function getTargetLang() {
|
| 244 |
+
return targetLangSelect.value === 'custom' ? targetLangCustom.value.trim() || '日本語' : targetLangSelect.value;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
// ── クリア・貼り付け ────────────────────────────────────────────
|
| 248 |
+
clearBtn.addEventListener('click', () => {
|
| 249 |
+
inputText.value = '';
|
| 250 |
+
charCount.textContent = '0 文字';
|
| 251 |
+
inputText.focus();
|
| 252 |
+
});
|
| 253 |
+
|
| 254 |
+
pasteBtn.addEventListener('click', async () => {
|
| 255 |
+
try {
|
| 256 |
+
const text = await navigator.clipboard.readText();
|
| 257 |
+
inputText.value = text;
|
| 258 |
+
charCount.textContent = `${text.length.toLocaleString()} 文字`;
|
| 259 |
+
} catch {
|
| 260 |
+
alert('クリップボードへのアクセスが許可されていません。');
|
| 261 |
+
}
|
| 262 |
+
});
|
| 263 |
+
|
| 264 |
+
// ── Ctrl+Enter ショートカット ──────────────────────────────────
|
| 265 |
+
inputText.addEventListener('keydown', (e) => {
|
| 266 |
+
if (e.ctrlKey && e.key === 'Enter') runTranslate();
|
| 267 |
+
});
|
| 268 |
+
|
| 269 |
+
// ── SSE 共通パーサー ────────────────────────────────────────────
|
| 270 |
+
async function consumeSSE(response, onData) {
|
| 271 |
+
const reader = response.body.getReader();
|
| 272 |
+
const decoder = new TextDecoder();
|
| 273 |
+
let buffer = '';
|
| 274 |
+
|
| 275 |
+
while (true) {
|
| 276 |
+
const { done, value } = await reader.read();
|
| 277 |
+
if (done) break;
|
| 278 |
+
buffer += decoder.decode(value, { stream: true });
|
| 279 |
+
const lines = buffer.split('\n');
|
| 280 |
+
buffer = lines.pop();
|
| 281 |
+
for (const line of lines) {
|
| 282 |
+
if (!line.startsWith('data: ')) continue;
|
| 283 |
+
try { onData(JSON.parse(line.slice(6))); } catch { /* ignore */ }
|
| 284 |
+
}
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
// ── 翻訳実行 ────────────────────────────────────────────────────
|
| 289 |
+
translateBtn.addEventListener('click', runTranslate);
|
| 290 |
+
|
| 291 |
+
async function runTranslate() {
|
| 292 |
+
const text = inputText.value.trim();
|
| 293 |
+
if (!text) { alert('翻訳するテキストを入力してください。'); return; }
|
| 294 |
+
|
| 295 |
+
setLoading(true);
|
| 296 |
+
outputArea.innerHTML = '';
|
| 297 |
+
outputPh.classList.add('hidden');
|
| 298 |
+
copyBtn.classList.add('hidden');
|
| 299 |
+
outputCharCount.textContent = '';
|
| 300 |
+
statusBar.textContent = '';
|
| 301 |
+
hidePanel();
|
| 302 |
+
|
| 303 |
+
const formData = new FormData();
|
| 304 |
+
formData.append('text', text);
|
| 305 |
+
formData.append('source_lang', getSourceLang());
|
| 306 |
+
formData.append('target_lang', getTargetLang());
|
| 307 |
+
|
| 308 |
+
try {
|
| 309 |
+
const response = await fetch('/translation/translate', { method: 'POST', body: formData });
|
| 310 |
+
if (!response.ok) throw new Error(`HTTP エラー: ${response.status}`);
|
| 311 |
+
|
| 312 |
+
await consumeSSE(response, (data) => {
|
| 313 |
+
if (data.status) {
|
| 314 |
+
showPanel(data.status, data.message, data.detail);
|
| 315 |
+
}
|
| 316 |
+
if (data.text !== undefined) {
|
| 317 |
+
hidePanel();
|
| 318 |
+
outputArea.textContent = data.text;
|
| 319 |
+
outputArea.scrollTop = outputArea.scrollHeight;
|
| 320 |
+
}
|
| 321 |
+
if (data.done) {
|
| 322 |
+
hidePanel();
|
| 323 |
+
statusBar.textContent = '翻訳完了';
|
| 324 |
+
copyBtn.classList.remove('hidden');
|
| 325 |
+
const len = outputArea.textContent.trim().length;
|
| 326 |
+
outputCharCount.textContent = `${len.toLocaleString()} 文字`;
|
| 327 |
+
}
|
| 328 |
+
if (data.error) {
|
| 329 |
+
hidePanel();
|
| 330 |
+
outputArea.innerHTML = `<p class="text-red-500 font-medium">${data.error}</p>`;
|
| 331 |
+
statusBar.textContent = 'エラー';
|
| 332 |
+
}
|
| 333 |
+
});
|
| 334 |
+
} catch (err) {
|
| 335 |
+
outputArea.innerHTML = `<p class="text-red-500 font-medium">エラーが発生しました: ${err.message}</p>`;
|
| 336 |
+
statusBar.textContent = 'エラー';
|
| 337 |
+
} finally {
|
| 338 |
+
setLoading(false);
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
// ── コピーボタン ────────────────────────────────────────────────
|
| 343 |
+
copyBtn.addEventListener('click', () => {
|
| 344 |
+
navigator.clipboard.writeText(outputArea.textContent).then(() => {
|
| 345 |
+
copyBtn.textContent = 'コピーしました!';
|
| 346 |
+
setTimeout(() => { copyBtn.textContent = 'コピー'; }, 2000);
|
| 347 |
+
});
|
| 348 |
+
});
|
| 349 |
+
|
| 350 |
+
// ── UI 状態管理 ─────────────────────────────────────────────────
|
| 351 |
+
function setLoading(loading) {
|
| 352 |
+
translateBtn.disabled = loading;
|
| 353 |
+
btnLabel.textContent = loading ? '翻訳中...' : '翻訳を実行';
|
| 354 |
+
btnIconRun.classList.toggle('hidden', loading);
|
| 355 |
+
btnIconSpin.classList.toggle('hidden', !loading);
|
| 356 |
+
}
|
| 357 |
+
</script>
|
| 358 |
+
{% endblock %}
|
MM_tools/app/blueprints/vlm/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VLM (Visual Language Model) ブループリント。"""
|
| 2 |
+
|
| 3 |
+
from flask import Blueprint
|
| 4 |
+
|
| 5 |
+
vlm_bp = Blueprint("vlm", __name__, template_folder="templates")
|
| 6 |
+
|
| 7 |
+
from . import routes # noqa: E402, F401
|
MM_tools/app/blueprints/vlm/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (395 Bytes). View file
|
|
|
MM_tools/app/blueprints/vlm/__pycache__/routes.cpython-314.pyc
ADDED
|
Binary file (6.12 kB). View file
|
|
|
MM_tools/app/blueprints/vlm/routes.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VLM ブループリント ルーティング。
|
| 3 |
+
|
| 4 |
+
④ VLM (Visual Language Model) ページ。
|
| 5 |
+
Qwen3-VL-2B-Instruct に画像とプロンプトを与え、SSE でトークンをストリーミング送信する。
|
| 6 |
+
|
| 7 |
+
SSE イベント:
|
| 8 |
+
{"status": "loading"|"processing", "message": "...", "detail": "..."}
|
| 9 |
+
{"text": "<トークン>"}
|
| 10 |
+
{"done": True}
|
| 11 |
+
{"error": "エラー内容"}
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import io
|
| 15 |
+
import json
|
| 16 |
+
import threading
|
| 17 |
+
|
| 18 |
+
from flask import render_template, request, Response, stream_with_context
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
from . import vlm_bp
|
| 22 |
+
from app.shared.models import get_qwen_model
|
| 23 |
+
|
| 24 |
+
# Qwen モデルは ledger と共用するため排他ロック
|
| 25 |
+
_model_lock = threading.Lock()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _sse(data: dict) -> str:
|
| 29 |
+
"""SSE フォーマットに変換する。"""
|
| 30 |
+
return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@vlm_bp.route("/")
|
| 34 |
+
def index():
|
| 35 |
+
"""VLM ページを返す。"""
|
| 36 |
+
return render_template("vlm/index.html")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@vlm_bp.route("/process", methods=["POST"])
|
| 40 |
+
def process():
|
| 41 |
+
"""
|
| 42 |
+
画像とプロンプトを受け取り Qwen3-VL で推論し SSE でストリーミング送信する。
|
| 43 |
+
|
| 44 |
+
Form data:
|
| 45 |
+
image (file): 画像ファイル
|
| 46 |
+
prompt (str): プロンプトテキスト
|
| 47 |
+
|
| 48 |
+
SSE イベント: モジュール docstring 参照
|
| 49 |
+
Returns:
|
| 50 |
+
text/event-stream
|
| 51 |
+
"""
|
| 52 |
+
image_file = request.files.get("image")
|
| 53 |
+
prompt = request.form.get("prompt", "").strip()
|
| 54 |
+
|
| 55 |
+
if not image_file or not image_file.filename:
|
| 56 |
+
def _err():
|
| 57 |
+
yield _sse({"error": "画像をアップロードしてください。"})
|
| 58 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 59 |
+
|
| 60 |
+
if not prompt:
|
| 61 |
+
def _err():
|
| 62 |
+
yield _sse({"error": "プロンプトを入力してください。"})
|
| 63 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 64 |
+
|
| 65 |
+
# SSE ジェネレータの遅延実行でリクエストストリームが閉じられる問題を防ぐため先読み
|
| 66 |
+
image_bytes = image_file.read()
|
| 67 |
+
|
| 68 |
+
def generate():
|
| 69 |
+
from transformers import TextIteratorStreamer
|
| 70 |
+
with _model_lock:
|
| 71 |
+
try:
|
| 72 |
+
# ── 画像読み込み ──
|
| 73 |
+
yield _sse({
|
| 74 |
+
"status": "processing",
|
| 75 |
+
"message": "画像を読み込み中...",
|
| 76 |
+
"detail": "",
|
| 77 |
+
})
|
| 78 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 79 |
+
|
| 80 |
+
# ── モデルロード ──
|
| 81 |
+
yield _sse({
|
| 82 |
+
"status": "loading",
|
| 83 |
+
"message": "モデルをロード中(初回のみ数分かかります)...",
|
| 84 |
+
"detail": "Qwen3-VL-2B-Instruct",
|
| 85 |
+
})
|
| 86 |
+
processor, model = get_qwen_model()
|
| 87 |
+
device = next(model.parameters()).device
|
| 88 |
+
|
| 89 |
+
yield _sse({
|
| 90 |
+
"status": "processing",
|
| 91 |
+
"message": "推論中...",
|
| 92 |
+
"detail": "テキストを生成しています",
|
| 93 |
+
})
|
| 94 |
+
|
| 95 |
+
# ── メッセージ構築 ──
|
| 96 |
+
messages = [
|
| 97 |
+
{
|
| 98 |
+
"role": "user",
|
| 99 |
+
"content": [
|
| 100 |
+
{"type": "image"},
|
| 101 |
+
{"type": "text", "text": prompt},
|
| 102 |
+
],
|
| 103 |
+
}
|
| 104 |
+
]
|
| 105 |
+
text_input = processor.apply_chat_template(
|
| 106 |
+
messages,
|
| 107 |
+
tokenize=False,
|
| 108 |
+
add_generation_prompt=True,
|
| 109 |
+
)
|
| 110 |
+
inputs = processor(
|
| 111 |
+
images=[image],
|
| 112 |
+
text=[text_input],
|
| 113 |
+
padding=True,
|
| 114 |
+
return_tensors="pt",
|
| 115 |
+
)
|
| 116 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 117 |
+
|
| 118 |
+
# ── ストリーミング生成 ──
|
| 119 |
+
streamer = TextIteratorStreamer(
|
| 120 |
+
processor.tokenizer,
|
| 121 |
+
skip_prompt=True,
|
| 122 |
+
skip_special_tokens=True,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
gen_kwargs = {
|
| 126 |
+
**inputs,
|
| 127 |
+
"max_new_tokens": 2048,
|
| 128 |
+
"do_sample": False,
|
| 129 |
+
"streamer": streamer,
|
| 130 |
+
}
|
| 131 |
+
gen_thread = threading.Thread(
|
| 132 |
+
target=model.generate,
|
| 133 |
+
kwargs=gen_kwargs,
|
| 134 |
+
daemon=True,
|
| 135 |
+
)
|
| 136 |
+
gen_thread.start()
|
| 137 |
+
|
| 138 |
+
for token in streamer:
|
| 139 |
+
if token:
|
| 140 |
+
yield _sse({"text": token})
|
| 141 |
+
|
| 142 |
+
gen_thread.join()
|
| 143 |
+
yield _sse({"done": True})
|
| 144 |
+
|
| 145 |
+
except Exception as exc:
|
| 146 |
+
yield _sse({"error": f"処理エラー: {exc}"})
|
| 147 |
+
|
| 148 |
+
response = Response(stream_with_context(generate()), mimetype="text/event-stream")
|
| 149 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 150 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 151 |
+
return response
|
MM_tools/app/blueprints/vlm/templates/vlm/index.html
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}AI Tools - VLM{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block head %}
|
| 6 |
+
<style>
|
| 7 |
+
/* ドロップゾーン */
|
| 8 |
+
#drop-zone {
|
| 9 |
+
border: 2px dashed #d97706;
|
| 10 |
+
transition: border-color 0.2s, background-color 0.2s;
|
| 11 |
+
}
|
| 12 |
+
#drop-zone.drag-over {
|
| 13 |
+
border-color: #f59e0b;
|
| 14 |
+
background-color: #fffbeb;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
/* 出力エリアのフェードイン */
|
| 18 |
+
@keyframes fadein {
|
| 19 |
+
from { opacity: 0; transform: translateY(4px); }
|
| 20 |
+
to { opacity: 1; transform: translateY(0); }
|
| 21 |
+
}
|
| 22 |
+
.token-fadein { animation: fadein 0.15s ease-out; }
|
| 23 |
+
|
| 24 |
+
/* ローディングスピナー */
|
| 25 |
+
.spinner {
|
| 26 |
+
width: 18px; height: 18px;
|
| 27 |
+
border: 2px solid #d97706;
|
| 28 |
+
border-top-color: transparent;
|
| 29 |
+
border-radius: 50%;
|
| 30 |
+
animation: spin 0.7s linear infinite;
|
| 31 |
+
display: inline-block;
|
| 32 |
+
}
|
| 33 |
+
@keyframes spin { to { transform: rotate(360deg); } }
|
| 34 |
+
|
| 35 |
+
/* ステータスバー */
|
| 36 |
+
#status-bar { transition: opacity 0.3s; }
|
| 37 |
+
</style>
|
| 38 |
+
{% endblock %}
|
| 39 |
+
|
| 40 |
+
{% block content %}
|
| 41 |
+
<main class="p-6 md:p-8">
|
| 42 |
+
|
| 43 |
+
<!-- ヘッダー -->
|
| 44 |
+
<div class="mb-6">
|
| 45 |
+
<div class="flex items-center gap-3 mb-1">
|
| 46 |
+
<span class="text-xs font-bold text-amber-600 bg-amber-50 border border-amber-200 px-2.5 py-0.5 rounded-full">④ VLM</span>
|
| 47 |
+
<h1 class="text-2xl font-bold text-gray-900">ビジュアル言語モデル</h1>
|
| 48 |
+
</div>
|
| 49 |
+
<p class="text-sm text-gray-500">画像をアップロードしてプロンプトで自由に指示。Qwen3-VL-2B-Instruct が回答します。</p>
|
| 50 |
+
</div>
|
| 51 |
+
|
| 52 |
+
<!-- ステータスバー -->
|
| 53 |
+
<div id="status-bar" class="hidden mb-4 flex items-center gap-2 text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-4 py-2.5">
|
| 54 |
+
<span class="spinner"></span>
|
| 55 |
+
<span id="status-msg">処理中...</span>
|
| 56 |
+
</div>
|
| 57 |
+
|
| 58 |
+
<!-- メイン 2カラム -->
|
| 59 |
+
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
| 60 |
+
|
| 61 |
+
<!-- ===== 左カラム: 入力 ===== -->
|
| 62 |
+
<div class="flex flex-col gap-5">
|
| 63 |
+
|
| 64 |
+
<!-- 画像アップロード -->
|
| 65 |
+
<div>
|
| 66 |
+
<label class="block text-sm font-semibold text-gray-700 mb-2">画像</label>
|
| 67 |
+
<div id="drop-zone"
|
| 68 |
+
class="relative rounded-xl bg-amber-50/50 cursor-pointer flex flex-col items-center justify-center gap-3 p-6 min-h-[200px]"
|
| 69 |
+
onclick="document.getElementById('file-input').click()">
|
| 70 |
+
<input id="file-input" type="file" accept="image/*" class="hidden" />
|
| 71 |
+
<!-- プレビュー(非表示時) -->
|
| 72 |
+
<div id="upload-placeholder" class="flex flex-col items-center gap-2 text-amber-600 pointer-events-none">
|
| 73 |
+
<svg class="w-12 h-12 opacity-60" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 74 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 75 |
+
d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909M3 16.5V18a2.25 2.25 0 002.25 2.25h13.5A2.25 2.25 0 0021 18v-1.5M16.5 6.75a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
|
| 76 |
+
</svg>
|
| 77 |
+
<p class="text-sm font-medium">クリックまたはドラッグ&ドロップ</p>
|
| 78 |
+
<p class="text-xs text-gray-400">PNG / JPG / WEBP など</p>
|
| 79 |
+
</div>
|
| 80 |
+
<!-- 画像プレビュー -->
|
| 81 |
+
<img id="preview-img" src="" alt="プレビュー"
|
| 82 |
+
class="hidden max-h-64 max-w-full rounded-lg object-contain shadow" />
|
| 83 |
+
</div>
|
| 84 |
+
<div id="file-info" class="hidden mt-1.5 text-xs text-gray-400"></div>
|
| 85 |
+
</div>
|
| 86 |
+
|
| 87 |
+
<!-- プロンプト -->
|
| 88 |
+
<div>
|
| 89 |
+
<label class="block text-sm font-semibold text-gray-700 mb-2">プロンプト</label>
|
| 90 |
+
|
| 91 |
+
<!-- プリセットボタン -->
|
| 92 |
+
<div class="flex flex-wrap gap-2 mb-2">
|
| 93 |
+
<button type="button" data-preset="この画像はどんな画像かテキストで出力してください"
|
| 94 |
+
class="preset-btn text-xs px-3 py-1.5 rounded-full border border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100 transition-colors font-medium">
|
| 95 |
+
画像の概要
|
| 96 |
+
</button>
|
| 97 |
+
<button type="button" data-preset="この画像の文字を読み取りどういう内容かまとめてテキストとして出力してください"
|
| 98 |
+
class="preset-btn text-xs px-3 py-1.5 rounded-full border border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100 transition-colors font-medium">
|
| 99 |
+
文字の読み取り・要約
|
| 100 |
+
</button>
|
| 101 |
+
<button type="button" data-preset="この画像を読み込んでテーブル(HTML形式)として出力してください"
|
| 102 |
+
class="preset-btn text-xs px-3 py-1.5 rounded-full border border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100 transition-colors font-medium">
|
| 103 |
+
テーブル (HTML)
|
| 104 |
+
</button>
|
| 105 |
+
<button type="button" id="free-btn"
|
| 106 |
+
class="text-xs px-3 py-1.5 rounded-full border border-gray-300 bg-gray-50 text-gray-600 hover:bg-gray-100 transition-colors font-medium">
|
| 107 |
+
フリー入力
|
| 108 |
+
</button>
|
| 109 |
+
</div>
|
| 110 |
+
|
| 111 |
+
<textarea id="prompt-input" rows="5"
|
| 112 |
+
placeholder="プロンプトを入力してください..."
|
| 113 |
+
class="w-full rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-800 resize-none
|
| 114 |
+
focus:outline-none focus:ring-2 focus:ring-amber-400 focus:border-transparent transition"
|
| 115 |
+
>この画像はどんな画像かテキストで出力してください</textarea>
|
| 116 |
+
</div>
|
| 117 |
+
|
| 118 |
+
<!-- 実行ボタン -->
|
| 119 |
+
<button id="run-btn"
|
| 120 |
+
class="w-full py-3 rounded-xl bg-amber-500 hover:bg-amber-600 active:scale-95 text-white font-bold text-sm
|
| 121 |
+
transition-all duration-150 shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2">
|
| 122 |
+
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 123 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M5 3l14 9-14 9V3z" />
|
| 124 |
+
</svg>
|
| 125 |
+
実行
|
| 126 |
+
</button>
|
| 127 |
+
|
| 128 |
+
</div>
|
| 129 |
+
|
| 130 |
+
<!-- ===== 右カラム: 出力 ===== -->
|
| 131 |
+
<div class="flex flex-col gap-3">
|
| 132 |
+
<div class="flex items-center justify-between">
|
| 133 |
+
<label class="block text-sm font-semibold text-gray-700">出力結果</label>
|
| 134 |
+
<button id="copy-btn"
|
| 135 |
+
class="hidden text-xs text-gray-400 hover:text-amber-600 flex items-center gap-1 transition-colors">
|
| 136 |
+
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 137 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 138 |
+
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
| 139 |
+
</svg>
|
| 140 |
+
コピー
|
| 141 |
+
</button>
|
| 142 |
+
</div>
|
| 143 |
+
|
| 144 |
+
<!-- 出力ボックス -->
|
| 145 |
+
<div id="output-box"
|
| 146 |
+
class="flex-1 min-h-[420px] rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm text-gray-700
|
| 147 |
+
overflow-y-auto leading-relaxed">
|
| 148 |
+
<p class="text-gray-300 text-center mt-16 select-none">実行すると結果がここに表示されます</p>
|
| 149 |
+
</div>
|
| 150 |
+
</div>
|
| 151 |
+
|
| 152 |
+
</div>
|
| 153 |
+
</main>
|
| 154 |
+
|
| 155 |
+
<script>
|
| 156 |
+
// ── ファイル選択 & ドラッグ & プレビュー ──────────────────────────────────
|
| 157 |
+
const dropZone = document.getElementById('drop-zone');
|
| 158 |
+
const fileInput = document.getElementById('file-input');
|
| 159 |
+
const previewImg = document.getElementById('preview-img');
|
| 160 |
+
const uploadPlaceholder = document.getElementById('upload-placeholder');
|
| 161 |
+
const fileInfo = document.getElementById('file-info');
|
| 162 |
+
|
| 163 |
+
function showPreview(file) {
|
| 164 |
+
const reader = new FileReader();
|
| 165 |
+
reader.onload = e => {
|
| 166 |
+
previewImg.src = e.target.result;
|
| 167 |
+
previewImg.classList.remove('hidden');
|
| 168 |
+
uploadPlaceholder.classList.add('hidden');
|
| 169 |
+
fileInfo.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
|
| 170 |
+
fileInfo.classList.remove('hidden');
|
| 171 |
+
};
|
| 172 |
+
reader.readAsDataURL(file);
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
fileInput.addEventListener('change', () => {
|
| 176 |
+
if (fileInput.files[0]) showPreview(fileInput.files[0]);
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
dropZone.addEventListener('dragover', e => {
|
| 180 |
+
e.preventDefault();
|
| 181 |
+
dropZone.classList.add('drag-over');
|
| 182 |
+
});
|
| 183 |
+
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
|
| 184 |
+
dropZone.addEventListener('drop', e => {
|
| 185 |
+
e.preventDefault();
|
| 186 |
+
dropZone.classList.remove('drag-over');
|
| 187 |
+
const file = e.dataTransfer.files[0];
|
| 188 |
+
if (file && file.type.startsWith('image/')) {
|
| 189 |
+
const dt = new DataTransfer();
|
| 190 |
+
dt.items.add(file);
|
| 191 |
+
fileInput.files = dt.files;
|
| 192 |
+
showPreview(file);
|
| 193 |
+
}
|
| 194 |
+
});
|
| 195 |
+
|
| 196 |
+
// ── プリセットボタン ──────────────────────────────────────────────────────
|
| 197 |
+
document.querySelectorAll('.preset-btn').forEach(btn => {
|
| 198 |
+
btn.addEventListener('click', () => {
|
| 199 |
+
document.getElementById('prompt-input').value = btn.dataset.preset;
|
| 200 |
+
});
|
| 201 |
+
});
|
| 202 |
+
document.getElementById('free-btn').addEventListener('click', () => {
|
| 203 |
+
document.getElementById('prompt-input').value = '';
|
| 204 |
+
document.getElementById('prompt-input').focus();
|
| 205 |
+
});
|
| 206 |
+
|
| 207 |
+
// ── 実行 ─────────────────────────────────────────────────────────────────
|
| 208 |
+
const runBtn = document.getElementById('run-btn');
|
| 209 |
+
const outputBox = document.getElementById('output-box');
|
| 210 |
+
const statusBar = document.getElementById('status-bar');
|
| 211 |
+
const statusMsg = document.getElementById('status-msg');
|
| 212 |
+
const copyBtn = document.getElementById('copy-btn');
|
| 213 |
+
|
| 214 |
+
// 生テキスト蓄積(コピー用)
|
| 215 |
+
let rawText = '';
|
| 216 |
+
|
| 217 |
+
function setStatus(msg, visible = true) {
|
| 218 |
+
statusMsg.textContent = msg;
|
| 219 |
+
statusBar.classList.toggle('hidden', !visible);
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
function renderOutput(text) {
|
| 223 |
+
// HTML タグが含まれていればそのまま innerHTML で描画
|
| 224 |
+
if (/<[a-zA-Z][^>]*>/.test(text)) {
|
| 225 |
+
outputBox.innerHTML = text;
|
| 226 |
+
} else {
|
| 227 |
+
outputBox.textContent = text;
|
| 228 |
+
}
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
runBtn.addEventListener('click', async () => {
|
| 232 |
+
if (!fileInput.files[0]) {
|
| 233 |
+
alert('画像をアップロードしてください。');
|
| 234 |
+
return;
|
| 235 |
+
}
|
| 236 |
+
const prompt = document.getElementById('prompt-input').value.trim();
|
| 237 |
+
if (!prompt) {
|
| 238 |
+
alert('プロンプトを入力してください。');
|
| 239 |
+
return;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
// リセット
|
| 243 |
+
rawText = '';
|
| 244 |
+
outputBox.innerHTML = '<p class="text-gray-300 text-center mt-16 select-none">処理中...</p>';
|
| 245 |
+
copyBtn.classList.add('hidden');
|
| 246 |
+
runBtn.disabled = true;
|
| 247 |
+
setStatus('モデルをロード中...');
|
| 248 |
+
|
| 249 |
+
const formData = new FormData();
|
| 250 |
+
formData.append('image', fileInput.files[0]);
|
| 251 |
+
formData.append('prompt', prompt);
|
| 252 |
+
|
| 253 |
+
try {
|
| 254 |
+
const resp = await fetch('/vlm/process', { method: 'POST', body: formData });
|
| 255 |
+
const reader = resp.body.getReader();
|
| 256 |
+
const decoder = new TextDecoder();
|
| 257 |
+
let buffer = '';
|
| 258 |
+
let outputStarted = false;
|
| 259 |
+
|
| 260 |
+
while (true) {
|
| 261 |
+
const { done, value } = await reader.read();
|
| 262 |
+
if (done) break;
|
| 263 |
+
|
| 264 |
+
buffer += decoder.decode(value, { stream: true });
|
| 265 |
+
const lines = buffer.split('\n');
|
| 266 |
+
buffer = lines.pop(); // 末尾の不完全な行を保持
|
| 267 |
+
|
| 268 |
+
for (const line of lines) {
|
| 269 |
+
if (!line.startsWith('data:')) continue;
|
| 270 |
+
let evt;
|
| 271 |
+
try { evt = JSON.parse(line.slice(5).trim()); } catch { continue; }
|
| 272 |
+
|
| 273 |
+
if (evt.status) {
|
| 274 |
+
setStatus(evt.message);
|
| 275 |
+
} else if (evt.text !== undefined) {
|
| 276 |
+
if (!outputStarted) {
|
| 277 |
+
outputBox.textContent = '';
|
| 278 |
+
outputStarted = true;
|
| 279 |
+
}
|
| 280 |
+
rawText += evt.text;
|
| 281 |
+
// ストリーミング中はプレーンテキストで逐次追加
|
| 282 |
+
outputBox.textContent = rawText;
|
| 283 |
+
outputBox.scrollTop = outputBox.scrollHeight;
|
| 284 |
+
} else if (evt.done) {
|
| 285 |
+
setStatus('完了', false);
|
| 286 |
+
// 完了後に HTML レンダリング判定
|
| 287 |
+
renderOutput(rawText);
|
| 288 |
+
copyBtn.classList.remove('hidden');
|
| 289 |
+
} else if (evt.error) {
|
| 290 |
+
setStatus('エラーが発生しました', false);
|
| 291 |
+
outputBox.innerHTML = `<p class="text-red-500">${evt.error}</p>`;
|
| 292 |
+
}
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
} catch (err) {
|
| 296 |
+
setStatus('通信エラー', false);
|
| 297 |
+
outputBox.innerHTML = `<p class="text-red-500">エラー: ${err.message}</p>`;
|
| 298 |
+
} finally {
|
| 299 |
+
runBtn.disabled = false;
|
| 300 |
+
statusBar.classList.add('hidden');
|
| 301 |
+
}
|
| 302 |
+
});
|
| 303 |
+
|
| 304 |
+
// ── コピー ───────────────────────────────────────────────────────────────
|
| 305 |
+
copyBtn.addEventListener('click', () => {
|
| 306 |
+
navigator.clipboard.writeText(rawText).then(() => {
|
| 307 |
+
const orig = copyBtn.innerHTML;
|
| 308 |
+
copyBtn.innerHTML = '<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg> コピー済み';
|
| 309 |
+
setTimeout(() => { copyBtn.innerHTML = orig; }, 1500);
|
| 310 |
+
});
|
| 311 |
+
});
|
| 312 |
+
</script>
|
| 313 |
+
{% endblock %}
|
MM_tools/app/blueprints/whisper/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint
|
| 2 |
+
|
| 3 |
+
whisper_bp = Blueprint("whisper", __name__, template_folder="templates")
|
| 4 |
+
|
| 5 |
+
from . import routes
|
MM_tools/app/blueprints/whisper/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (339 Bytes). View file
|
|
|
MM_tools/app/blueprints/whisper/__pycache__/routes.cpython-314.pyc
ADDED
|
Binary file (8.48 kB). View file
|
|
|
MM_tools/app/blueprints/whisper/engine/__init__.py
ADDED
|
File without changes
|
MM_tools/app/blueprints/whisper/engine/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (175 Bytes). View file
|
|
|
MM_tools/app/blueprints/whisper/engine/__pycache__/core.cpython-314.pyc
ADDED
|
Binary file (8.34 kB). View file
|
|
|
MM_tools/app/blueprints/whisper/engine/core.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Whisper 音声認識コアモジュール。
|
| 3 |
+
|
| 4 |
+
翻訳は共有の Gemma-1b (CTranslate2) を使用する。
|
| 5 |
+
|
| 6 |
+
SSE イベント形式:
|
| 7 |
+
{"status": "loading"|"processing", "message": "...", "detail": "..."}
|
| 8 |
+
{"type": "info", "text": "言語推定結果など"}
|
| 9 |
+
{"type": "segment", "time": "[0s → 5s]"|"", "text": "認識テキスト"}
|
| 10 |
+
{"done": True, "elapsed": 12.3}
|
| 11 |
+
{"error": "エラー内容"}
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 20 |
+
# 内部ユーティリティ
|
| 21 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 22 |
+
|
| 23 |
+
def _sse(data: dict) -> str:
|
| 24 |
+
"""dict を SSE data 行に変換する。"""
|
| 25 |
+
return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _time_label(seconds: float) -> str:
|
| 29 |
+
"""秒数を 'Xm Ys' 形式の文字列に変換する。"""
|
| 30 |
+
if seconds >= 3600:
|
| 31 |
+
h = int(seconds // 3600)
|
| 32 |
+
m = int((seconds % 3600) // 60)
|
| 33 |
+
s = int(seconds % 60)
|
| 34 |
+
return f"{h}h {m}m {s}s"
|
| 35 |
+
if seconds >= 60:
|
| 36 |
+
m = int(seconds // 60)
|
| 37 |
+
s = int(seconds % 60)
|
| 38 |
+
return f"{m}m {s}s"
|
| 39 |
+
return f"{int(seconds)}s"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _append_file(path: Path, text: str, first: bool) -> None:
|
| 43 |
+
"""テキストをファイルに追記(初回は新規作成)する。"""
|
| 44 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
with path.open("w" if first else "a", encoding="utf-8") as f:
|
| 46 |
+
f.write(text + "\n")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _translate(text: str, target_lang: str) -> str:
|
| 50 |
+
"""
|
| 51 |
+
LFM 2.5 (ONNX) で指定言語に翻訳する。
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
text: 翻訳対象テキスト
|
| 55 |
+
target_lang: 翻訳先言語名(例: "英語", "English", "中国語")
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
str: 翻訳済みテキスト
|
| 59 |
+
"""
|
| 60 |
+
from app.shared.models import get_lfm, get_lfm_lock
|
| 61 |
+
system_prompt = (
|
| 62 |
+
f"あなたはプロの翻訳者です。"
|
| 63 |
+
f"与えられた文章を{target_lang}に翻訳してください。"
|
| 64 |
+
"翻訳文のみを出力してください。説明や補足は不要です。"
|
| 65 |
+
)
|
| 66 |
+
with get_lfm_lock():
|
| 67 |
+
llm = get_lfm()
|
| 68 |
+
return llm.generate(user_prompt=text, system_prompt=system_prompt)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 72 |
+
# 公開関数
|
| 73 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 74 |
+
|
| 75 |
+
def voice2character_yield_with_timestamp(
|
| 76 |
+
file_path: str,
|
| 77 |
+
model,
|
| 78 |
+
export_dir: Path,
|
| 79 |
+
trg_lang: str | None = None,
|
| 80 |
+
):
|
| 81 |
+
"""
|
| 82 |
+
タイムスタンプ付きで文字起こしを行い、SSE イベントをジェネレートする。
|
| 83 |
+
出力ファイル: whisper_text_time.txt
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
file_path: 音声ファイルのパス
|
| 87 |
+
model: faster-whisper WhisperModel インスタンス
|
| 88 |
+
export_dir: テキスト書き出し先ディレクトリ
|
| 89 |
+
trg_lang: 翻訳先言語名(例: "英語")。None なら翻訳しない
|
| 90 |
+
"""
|
| 91 |
+
timer = time.time()
|
| 92 |
+
segments, info = model.transcribe(file_path, beam_size=5, vad_filter=True)
|
| 93 |
+
|
| 94 |
+
yield _sse({"type": "info",
|
| 95 |
+
"text": f"書き出し元言語:「{info.language}」({info.language_probability * 100:.1f}%)"})
|
| 96 |
+
|
| 97 |
+
for i, segment in enumerate(segments):
|
| 98 |
+
text = segment.text.strip()
|
| 99 |
+
if not text:
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
if trg_lang:
|
| 103 |
+
try:
|
| 104 |
+
translated = _translate(text, trg_lang)
|
| 105 |
+
text = f"{translated} (原文: {text})"
|
| 106 |
+
except Exception as exc:
|
| 107 |
+
yield _sse({"type": "info", "text": f"翻訳エラー(セグメント {i}): {exc}"})
|
| 108 |
+
|
| 109 |
+
time_str = f"[{_time_label(segment.start)} → {_time_label(segment.end)}]"
|
| 110 |
+
_append_file(export_dir / "whisper_text_time.txt", f"{time_str} {text}", first=(i == 0))
|
| 111 |
+
|
| 112 |
+
yield _sse({"type": "segment", "time": time_str, "text": text})
|
| 113 |
+
|
| 114 |
+
yield _sse({"done": True, "elapsed": round(time.time() - timer, 1)})
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def voice2character_yield_no_timestamp(
|
| 118 |
+
file_path: str,
|
| 119 |
+
model,
|
| 120 |
+
export_dir: Path,
|
| 121 |
+
trg_lang: str | None = None,
|
| 122 |
+
):
|
| 123 |
+
"""
|
| 124 |
+
タイムスタンプなしで文字起こしを行い、SSE イベントをジェネレートす���。
|
| 125 |
+
出力ファイル: whisper_only_text.txt
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
file_path: 音声ファイルのパス
|
| 129 |
+
model: faster-whisper WhisperModel インスタンス
|
| 130 |
+
export_dir: テキスト書き出し先ディレクトリ
|
| 131 |
+
trg_lang: 翻訳先言語名(例: "英語")。None なら翻訳しない
|
| 132 |
+
"""
|
| 133 |
+
timer = time.time()
|
| 134 |
+
segments, info = model.transcribe(file_path, beam_size=5, vad_filter=True)
|
| 135 |
+
|
| 136 |
+
yield _sse({"type": "info",
|
| 137 |
+
"text": f"書き出し元言語:「{info.language}」({info.language_probability * 100:.1f}%)"})
|
| 138 |
+
|
| 139 |
+
for i, segment in enumerate(segments):
|
| 140 |
+
text = segment.text.strip()
|
| 141 |
+
if not text:
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
if trg_lang:
|
| 145 |
+
try:
|
| 146 |
+
translated = _translate(text, trg_lang)
|
| 147 |
+
text = f"{translated} (原文: {text})"
|
| 148 |
+
except Exception as exc:
|
| 149 |
+
yield _sse({"type": "info", "text": f"翻訳エラー(セグメント {i}): {exc}"})
|
| 150 |
+
|
| 151 |
+
_append_file(export_dir / "whisper_only_text.txt", text, first=(i == 0))
|
| 152 |
+
|
| 153 |
+
yield _sse({"type": "segment", "time": "", "text": text})
|
| 154 |
+
|
| 155 |
+
yield _sse({"done": True, "elapsed": round(time.time() - timer, 1)})
|
MM_tools/app/blueprints/whisper/engine/punctuation.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
日本語句読点予測モジュール(遅延ロード)。
|
| 3 |
+
|
| 4 |
+
BERT (tohoku-nlp/bert-base-japanese-char-v3) + カスタム重みで
|
| 5 |
+
句点(。)・読点(、)を文中に挿入する。
|
| 6 |
+
|
| 7 |
+
重みファイル: <project_root>/WhisperApp/weight/punctuation_position_model.pth
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[5] # AI-OCR/
|
| 14 |
+
WEIGHT_PATH = ROOT / "WhisperApp" / "weight" / "punctuation_position_model.pth"
|
| 15 |
+
|
| 16 |
+
_tokenizer = None
|
| 17 |
+
_model = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _load() -> None:
|
| 21 |
+
"""BERT モデルと重みを遅延ロードする。"""
|
| 22 |
+
global _tokenizer, _model
|
| 23 |
+
if _model is not None:
|
| 24 |
+
return
|
| 25 |
+
|
| 26 |
+
from transformers import BertTokenizer, BertModel
|
| 27 |
+
|
| 28 |
+
model_name = "tohoku-nlp/bert-base-japanese-char-v3"
|
| 29 |
+
_tokenizer = BertTokenizer.from_pretrained(model_name)
|
| 30 |
+
base_model = BertModel.from_pretrained(model_name)
|
| 31 |
+
|
| 32 |
+
_model = _PunctuationPredictor(base_model)
|
| 33 |
+
_model.load_state_dict(
|
| 34 |
+
torch.load(str(WEIGHT_PATH), map_location="cpu", weights_only=True)
|
| 35 |
+
)
|
| 36 |
+
_model.eval()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class _PunctuationPredictor(torch.nn.Module):
|
| 40 |
+
"""BERT ベースの句読点予測モデル。"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, base_model):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.base_model = base_model
|
| 45 |
+
self.dropout = torch.nn.Dropout(0.2)
|
| 46 |
+
self.linear = torch.nn.Linear(768, 2)
|
| 47 |
+
|
| 48 |
+
def forward(self, input_ids, attention_mask):
|
| 49 |
+
last_hidden = self.base_model(
|
| 50 |
+
input_ids=input_ids, attention_mask=attention_mask
|
| 51 |
+
).last_hidden_state
|
| 52 |
+
return self.linear(self.dropout(last_hidden))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _insert_punctuation(input_ids, comma_pos, period_pos) -> str:
|
| 56 |
+
"""予測ポジションに基づいて句読点を挿入する。"""
|
| 57 |
+
text = []
|
| 58 |
+
for i, (c, p) in enumerate(zip(comma_pos, period_pos)):
|
| 59 |
+
token_id = input_ids[i].item()
|
| 60 |
+
if token_id > 5 and i < len(input_ids) - 1:
|
| 61 |
+
char = _tokenizer.ids_to_tokens[token_id]
|
| 62 |
+
if p:
|
| 63 |
+
text.append(char + "。")
|
| 64 |
+
elif c:
|
| 65 |
+
text.append(char + "、")
|
| 66 |
+
else:
|
| 67 |
+
text.append(char)
|
| 68 |
+
return "".join(text)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def process_long_text(
|
| 72 |
+
text: str,
|
| 73 |
+
max_length: int = 256,
|
| 74 |
+
comma_thresh: float = 0.1,
|
| 75 |
+
period_thresh: float = 0.1,
|
| 76 |
+
) -> str:
|
| 77 |
+
"""
|
| 78 |
+
長文を分割しながら句読点を挿入して返す。
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
text: 句読点なしの日本語テキスト
|
| 82 |
+
max_length: 一度に処理する文字数
|
| 83 |
+
comma_thresh: 読点挿入の閾値
|
| 84 |
+
period_thresh: 句点挿入の閾値
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
str: 句読点挿入済みテキスト
|
| 88 |
+
"""
|
| 89 |
+
_load()
|
| 90 |
+
text = text.replace("、", "").replace("。", "")
|
| 91 |
+
result = ""
|
| 92 |
+
|
| 93 |
+
for i in range(0, len(text), max_length):
|
| 94 |
+
chunk = text[i : i + max_length]
|
| 95 |
+
inputs = _tokenizer(
|
| 96 |
+
" ".join(list(chunk)),
|
| 97 |
+
max_length=512,
|
| 98 |
+
padding="max_length",
|
| 99 |
+
truncation=True,
|
| 100 |
+
return_tensors="pt",
|
| 101 |
+
)
|
| 102 |
+
with torch.no_grad():
|
| 103 |
+
output = _model(inputs.input_ids, inputs.attention_mask)
|
| 104 |
+
|
| 105 |
+
output = torch.sigmoid(output)
|
| 106 |
+
comma_pos = output[0].detach().numpy().T[0] > comma_thresh
|
| 107 |
+
period_pos = output[0].detach().numpy().T[1] > period_thresh
|
| 108 |
+
result += _insert_punctuation(inputs.input_ids[0], comma_pos, period_pos)
|
| 109 |
+
|
| 110 |
+
return result
|
MM_tools/app/blueprints/whisper/engine/translator.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
M2M100 418M CTranslate2 翻訳モジュール(遅延ロード)。
|
| 3 |
+
|
| 4 |
+
モデルパス優先順:
|
| 5 |
+
1. <project_root>/models/m2m100_418M_int8/
|
| 6 |
+
2. C:/Users/showe/Desktop/python/仕事関係/量子化Transformer/m2m100_418M_int8/
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[5] # AI-OCR/
|
| 12 |
+
|
| 13 |
+
_PRIMARY_PATH = ROOT / "models" / "m2m100_418M_int8"
|
| 14 |
+
_FALLBACK_PATH = Path(r"C:\Users\showe\Desktop\python\仕事関係\量子化Transformer\m2m100_418M_int8")
|
| 15 |
+
|
| 16 |
+
_instance = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_m2m100() -> "_M2M100Translator":
|
| 20 |
+
"""
|
| 21 |
+
M2M100 翻訳モデルを遅延ロードして返す。
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
_M2M100Translator: 翻訳モデルインスタンス
|
| 25 |
+
|
| 26 |
+
Raises:
|
| 27 |
+
FileNotFoundError: モデルディレクトリが見つからない場合
|
| 28 |
+
"""
|
| 29 |
+
global _instance
|
| 30 |
+
if _instance is None:
|
| 31 |
+
_instance = _M2M100Translator()
|
| 32 |
+
return _instance
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _M2M100Translator:
|
| 36 |
+
"""CTranslate2 M2M100 418M を用いた多言語翻訳クラス。"""
|
| 37 |
+
|
| 38 |
+
def __init__(self):
|
| 39 |
+
import ctranslate2
|
| 40 |
+
import transformers
|
| 41 |
+
|
| 42 |
+
model_path = (
|
| 43 |
+
str(_PRIMARY_PATH) if _PRIMARY_PATH.exists() else str(_FALLBACK_PATH)
|
| 44 |
+
)
|
| 45 |
+
if not Path(model_path).exists():
|
| 46 |
+
raise FileNotFoundError(
|
| 47 |
+
f"M2M100 モデルが見つかりません。\n"
|
| 48 |
+
f" 確認パス1: {_PRIMARY_PATH}\n"
|
| 49 |
+
f" 確認パス2: {_FALLBACK_PATH}"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
self._translator = ctranslate2.Translator(model_path)
|
| 53 |
+
self._tokenizer = transformers.AutoTokenizer.from_pretrained("facebook/m2m100_418M")
|
| 54 |
+
|
| 55 |
+
def translate(self, text: str, src_lang: str = "en", trg_lang: str = "ja") -> str:
|
| 56 |
+
"""
|
| 57 |
+
テキストを指定言語に翻訳する。
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
text: 翻訳対象テキスト
|
| 61 |
+
src_lang: 原文言語コード(例: "ja", "en", "zh")
|
| 62 |
+
trg_lang: 翻訳先言語コード
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
str: 翻訳済みテキスト
|
| 66 |
+
"""
|
| 67 |
+
self._tokenizer.src_lang = src_lang
|
| 68 |
+
tokens = self._tokenizer.convert_ids_to_tokens(self._tokenizer.encode(text))
|
| 69 |
+
prefix = [self._tokenizer.lang_code_to_token[trg_lang]]
|
| 70 |
+
results = self._translator.translate_batch(
|
| 71 |
+
[tokens],
|
| 72 |
+
target_prefix=[prefix],
|
| 73 |
+
max_decoding_length=512,
|
| 74 |
+
)
|
| 75 |
+
return self._tokenizer.decode(
|
| 76 |
+
self._tokenizer.convert_tokens_to_ids(results[0].hypotheses[0][1:])
|
| 77 |
+
)
|
MM_tools/app/blueprints/whisper/routes.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
whisper ブループリント ルーティング。
|
| 3 |
+
|
| 4 |
+
④ 音声文字起こしページ。
|
| 5 |
+
faster-whisper で音声/動画ファイルからテキストを抽出し SSE でストリーミング送信する。
|
| 6 |
+
翻訳オプションは LFM 2.5 (ONNX) を使用する。
|
| 7 |
+
|
| 8 |
+
SSE イベント:
|
| 9 |
+
{"status": "loading"|"processing", "message": "...", "detail": "..."}
|
| 10 |
+
{"type": "info", "text": "言語推定など"}
|
| 11 |
+
{"type": "segment", "time": "[0s → 5s]", "text": "テキスト"}
|
| 12 |
+
{"done": True, "elapsed": 12.3}
|
| 13 |
+
{"error": "エラー内容"}
|
| 14 |
+
|
| 15 |
+
設定変更: config.py の UPLOAD_DIR / EXPORT_DIR / WHISPER_*_ID を参照。
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
from flask import render_template, request, Response, stream_with_context, send_file
|
| 22 |
+
|
| 23 |
+
from . import whisper_bp
|
| 24 |
+
from app.shared.models import (
|
| 25 |
+
get_whisper_small,
|
| 26 |
+
get_whisper_large,
|
| 27 |
+
is_whisper_small_loaded,
|
| 28 |
+
is_whisper_large_loaded,
|
| 29 |
+
)
|
| 30 |
+
from config import UPLOAD_DIR, EXPORT_DIR
|
| 31 |
+
|
| 32 |
+
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
EXPORT_DIR.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
|
| 35 |
+
_ALLOWED_EXTS = {"mp3", "wav", "mp4", "m4a", "ogg", "webm"}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _sse(data: dict) -> str:
|
| 39 |
+
return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@whisper_bp.route("/")
|
| 43 |
+
def index():
|
| 44 |
+
"""文字起こしページを返す。"""
|
| 45 |
+
return render_template("whisper/index.html")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@whisper_bp.route("/upload", methods=["POST"])
|
| 49 |
+
def upload():
|
| 50 |
+
"""
|
| 51 |
+
音声/動画ファイルをアップロードしてサーバーに保存する。
|
| 52 |
+
|
| 53 |
+
Form data:
|
| 54 |
+
file (file): 音声・動画ファイル (.mp3 .wav .mp4 .m4a .ogg .webm)
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
JSON: {"message": "...", "filename": "..."} または {"error": "..."}
|
| 58 |
+
"""
|
| 59 |
+
if "file" not in request.files or request.files["file"].filename == "":
|
| 60 |
+
return {"error": "ファイルが選択されていません"}, 400
|
| 61 |
+
|
| 62 |
+
file = request.files["file"]
|
| 63 |
+
ext = os.path.splitext(file.filename)[-1].lstrip(".").lower()
|
| 64 |
+
|
| 65 |
+
if ext not in _ALLOWED_EXTS:
|
| 66 |
+
return {"error": f"対応していない形式です: .{ext}"}, 400
|
| 67 |
+
|
| 68 |
+
# 既存の音声ファイルをクリア
|
| 69 |
+
for old in UPLOAD_DIR.glob("audio.*"):
|
| 70 |
+
old.unlink(missing_ok=True)
|
| 71 |
+
|
| 72 |
+
save_path = UPLOAD_DIR / f"audio.{ext}"
|
| 73 |
+
file.save(str(save_path))
|
| 74 |
+
return {"message": "アップロード完了", "filename": file.filename}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@whisper_bp.route("/process", methods=["POST"])
|
| 78 |
+
def process():
|
| 79 |
+
"""
|
| 80 |
+
アップロード済み音声を文字起こしして SSE でストリーミング送信する。
|
| 81 |
+
|
| 82 |
+
JSON body:
|
| 83 |
+
model_type (str): "Small" | "Large"
|
| 84 |
+
mode_type (str): "タイムスタンプあり" | "タイムスタンプなし"
|
| 85 |
+
trg_lang (str): 翻訳先言語名(空文字なら翻訳なし)
|
| 86 |
+
|
| 87 |
+
SSE イベント: モジュール docstring 参照
|
| 88 |
+
Returns:
|
| 89 |
+
text/event-stream
|
| 90 |
+
"""
|
| 91 |
+
data = request.get_json() or {}
|
| 92 |
+
model_type = data.get("model_type", "Small")
|
| 93 |
+
mode_type = data.get("mode_type", "タイムスタンプあり")
|
| 94 |
+
trg_lang = data.get("trg_lang", "").strip() or None
|
| 95 |
+
is_ts = (mode_type == "タイムスタンプあり")
|
| 96 |
+
|
| 97 |
+
audio_files = list(UPLOAD_DIR.glob("audio.*"))
|
| 98 |
+
if not audio_files:
|
| 99 |
+
def _err():
|
| 100 |
+
yield _sse({"error": "音声ファイルが見つかりません。先にアップロードしてください。"})
|
| 101 |
+
return Response(stream_with_context(_err()), mimetype="text/event-stream")
|
| 102 |
+
|
| 103 |
+
file_path = str(audio_files[0])
|
| 104 |
+
|
| 105 |
+
def generate():
|
| 106 |
+
is_small = (model_type == "Small")
|
| 107 |
+
is_loaded = is_whisper_small_loaded() if is_small else is_whisper_large_loaded()
|
| 108 |
+
name = "Whisper Small" if is_small else "Whisper Large-v3-turbo"
|
| 109 |
+
|
| 110 |
+
if not is_loaded:
|
| 111 |
+
yield _sse({
|
| 112 |
+
"status": "loading",
|
| 113 |
+
"message": f"{name} モデルをロード中...",
|
| 114 |
+
"detail": "初回のみ数分かかります。しばらくお待ちください。",
|
| 115 |
+
})
|
| 116 |
+
else:
|
| 117 |
+
yield _sse({
|
| 118 |
+
"status": "processing",
|
| 119 |
+
"message": "文字起こしを開始します...",
|
| 120 |
+
"detail": f"モード: {mode_type}",
|
| 121 |
+
})
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
model = get_whisper_small() if is_small else get_whisper_large()
|
| 125 |
+
except Exception as exc:
|
| 126 |
+
yield _sse({"error": f"モデルのロードに失敗しました: {exc}"})
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
yield _sse({
|
| 130 |
+
"status": "processing",
|
| 131 |
+
"message": "音声を解析中...",
|
| 132 |
+
"detail": "音声認識を実行しています",
|
| 133 |
+
})
|
| 134 |
+
|
| 135 |
+
from .engine.core import (
|
| 136 |
+
voice2character_yield_with_timestamp,
|
| 137 |
+
voice2character_yield_no_timestamp,
|
| 138 |
+
)
|
| 139 |
+
fn = voice2character_yield_with_timestamp if is_ts else voice2character_yield_no_timestamp
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
yield from fn(file_path, model, export_dir=EXPORT_DIR, trg_lang=trg_lang)
|
| 143 |
+
except Exception as exc:
|
| 144 |
+
yield _sse({"error": f"文字起こしエラー: {exc}"})
|
| 145 |
+
|
| 146 |
+
response = Response(stream_with_context(generate()), mimetype="text/event-stream")
|
| 147 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 148 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 149 |
+
return response
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@whisper_bp.route("/download")
|
| 153 |
+
def download():
|
| 154 |
+
"""
|
| 155 |
+
文字起こし結果テキストをダウンロードする。
|
| 156 |
+
|
| 157 |
+
Query params:
|
| 158 |
+
type (str): "text_time" | "text_only" | "minutes"
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
file attachment
|
| 162 |
+
"""
|
| 163 |
+
file_map = {
|
| 164 |
+
"text_time": "whisper_text_time.txt",
|
| 165 |
+
"text_only": "whisper_only_text.txt",
|
| 166 |
+
"minutes": "whisper_minutes.txt",
|
| 167 |
+
}
|
| 168 |
+
file_type = request.args.get("type", "text_time")
|
| 169 |
+
filename = file_map.get(file_type, "whisper_text_time.txt")
|
| 170 |
+
path = EXPORT_DIR / filename
|
| 171 |
+
|
| 172 |
+
if not path.exists():
|
| 173 |
+
return {"error": "ファイルが見つかりません。先に書き出しを実行してください。"}, 404
|
| 174 |
+
|
| 175 |
+
return send_file(str(path), as_attachment=True, download_name=filename)
|
MM_tools/app/blueprints/whisper/templates/whisper/index.html
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}音声文字起こし - AI Tools{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block head %}
|
| 6 |
+
<style>
|
| 7 |
+
/* グロー枠(Small: シアン、Large: レッド) */
|
| 8 |
+
.whisper-card {
|
| 9 |
+
border: 2px solid #22d3ee;
|
| 10 |
+
box-shadow: 0 0 20px rgba(0, 255, 255, 0.35);
|
| 11 |
+
transition: border-color 0.5s ease, box-shadow 0.5s ease;
|
| 12 |
+
}
|
| 13 |
+
.whisper-card.large-mode {
|
| 14 |
+
border-color: #f87171;
|
| 15 |
+
box-shadow: 0 0 20px rgba(255, 80, 80, 0.4);
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
/* 結果行フェードイン */
|
| 19 |
+
@keyframes fadeIn {
|
| 20 |
+
from { opacity: 0; transform: translateY(-3px); }
|
| 21 |
+
to { opacity: 1; transform: translateY(0); }
|
| 22 |
+
}
|
| 23 |
+
.result-row { animation: fadeIn 0.35s ease-out; }
|
| 24 |
+
|
| 25 |
+
/* ドロップゾーン */
|
| 26 |
+
#drop-area.drag-over {
|
| 27 |
+
background-color: #ecfeff;
|
| 28 |
+
border-color: #22d3ee;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
/* 結果コンテナスクロールバー */
|
| 32 |
+
#result-container::-webkit-scrollbar { width: 6px; }
|
| 33 |
+
#result-container::-webkit-scrollbar-track { background: #f1f5f9; }
|
| 34 |
+
#result-container::-webkit-scrollbar-thumb { background: #67e8f9; border-radius: 3px; }
|
| 35 |
+
</style>
|
| 36 |
+
{% endblock %}
|
| 37 |
+
|
| 38 |
+
{% block content %}
|
| 39 |
+
<main class="max-w-6xl mx-auto px-6 py-8">
|
| 40 |
+
|
| 41 |
+
<!-- ページタイトル -->
|
| 42 |
+
<div class="flex items-center gap-3 mb-6">
|
| 43 |
+
<div class="w-9 h-9 rounded-lg bg-cyan-700 flex items-center justify-center">
|
| 44 |
+
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 45 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 46 |
+
d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
|
| 47 |
+
</svg>
|
| 48 |
+
</div>
|
| 49 |
+
<div>
|
| 50 |
+
<h1 class="text-2xl font-bold text-gray-900">音声文字起こし</h1>
|
| 51 |
+
<p class="text-sm text-gray-400">Whisper (faster-whisper) によるローカル音声認識</p>
|
| 52 |
+
</div>
|
| 53 |
+
</div>
|
| 54 |
+
|
| 55 |
+
<!-- メインカード(グロー枠) -->
|
| 56 |
+
<div id="whisper-card" class="whisper-card relative rounded-xl bg-white overflow-hidden">
|
| 57 |
+
|
| 58 |
+
<!-- 処理中スピナー(右上) -->
|
| 59 |
+
<div id="spinner" class="hidden absolute top-3 right-3 z-10">
|
| 60 |
+
<svg id="spinner-svg" class="w-7 h-7 animate-spin text-cyan-500" fill="none" viewBox="0 0 24 24">
|
| 61 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
| 62 |
+
<path class="opacity-75" fill="currentColor"
|
| 63 |
+
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
|
| 64 |
+
</path>
|
| 65 |
+
</svg>
|
| 66 |
+
</div>
|
| 67 |
+
|
| 68 |
+
<!-- ファイルドロップゾーン -->
|
| 69 |
+
<div id="drop-area"
|
| 70 |
+
class="m-4 border-2 border-dashed border-gray-300 rounded-xl p-6 text-center cursor-pointer
|
| 71 |
+
transition-colors hover:border-cyan-400 hover:bg-cyan-50 select-none"
|
| 72 |
+
onclick="document.getElementById('file_input').click()">
|
| 73 |
+
<input id="file_input" type="file" accept=".mp3,.wav,.mp4,.m4a,.ogg,.webm" class="hidden">
|
| 74 |
+
|
| 75 |
+
<!-- 未選択時 -->
|
| 76 |
+
<div id="drop-placeholder" class="flex flex-col items-center gap-2 text-gray-400">
|
| 77 |
+
<svg class="w-10 h-10" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 78 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 79 |
+
d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3" />
|
| 80 |
+
</svg>
|
| 81 |
+
<p class="text-sm font-medium">音声・動画ファイルをドロップ、またはクリックして選択</p>
|
| 82 |
+
<p class="text-xs text-gray-300">.mp3 .wav .mp4 .m4a .ogg</p>
|
| 83 |
+
</div>
|
| 84 |
+
|
| 85 |
+
<!-- 選択後 -->
|
| 86 |
+
<div id="file-info" class="hidden items-center justify-center gap-3 text-gray-700">
|
| 87 |
+
<svg class="w-8 h-8 text-cyan-500 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
| 88 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 89 |
+
d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3" />
|
| 90 |
+
</svg>
|
| 91 |
+
<div class="text-left">
|
| 92 |
+
<p id="file-name" class="font-semibold text-sm"></p>
|
| 93 |
+
<p id="file-size" class="text-xs text-gray-400"></p>
|
| 94 |
+
</div>
|
| 95 |
+
<svg class="w-5 h-5 text-green-500 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 96 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
|
| 97 |
+
</svg>
|
| 98 |
+
</div>
|
| 99 |
+
</div>
|
| 100 |
+
|
| 101 |
+
<!-- オプション行 -->
|
| 102 |
+
<div class="flex flex-wrap gap-4 px-4 pb-4">
|
| 103 |
+
|
| 104 |
+
<!-- モデル選択 -->
|
| 105 |
+
<div class="flex flex-col gap-2 border border-gray-200 rounded-lg px-4 py-3 min-w-[180px]">
|
| 106 |
+
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wide">モデル</p>
|
| 107 |
+
<div class="flex gap-5 text-sm">
|
| 108 |
+
<label class="flex items-center gap-1.5 cursor-pointer">
|
| 109 |
+
<input type="radio" name="model" value="Small" checked class="accent-cyan-500">
|
| 110 |
+
<span class="font-medium">Small</span>
|
| 111 |
+
<span class="text-xs text-gray-400">高速</span>
|
| 112 |
+
</label>
|
| 113 |
+
<label class="flex items-center gap-1.5 cursor-pointer">
|
| 114 |
+
<input type="radio" name="model" value="Large" class="accent-red-500">
|
| 115 |
+
<span class="font-medium">Large</span>
|
| 116 |
+
<span class="text-xs text-gray-400">高精度</span>
|
| 117 |
+
</label>
|
| 118 |
+
</div>
|
| 119 |
+
</div>
|
| 120 |
+
|
| 121 |
+
<!-- モード選択 -->
|
| 122 |
+
<div class="flex flex-col gap-2 border border-gray-200 rounded-lg px-4 py-3 min-w-[240px]">
|
| 123 |
+
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wide">出力形式</p>
|
| 124 |
+
<div class="flex gap-5 text-sm">
|
| 125 |
+
<label class="flex items-center gap-1.5 cursor-pointer">
|
| 126 |
+
<input type="radio" name="mode" value="タイムスタンプあり" checked class="accent-cyan-500">
|
| 127 |
+
<span class="font-medium">タイムスタンプあり</span>
|
| 128 |
+
</label>
|
| 129 |
+
<label class="flex items-center gap-1.5 cursor-pointer">
|
| 130 |
+
<input type="radio" name="mode" value="タイムスタンプなし" class="accent-cyan-500">
|
| 131 |
+
<span class="font-medium">タイムスタンプなし</span>
|
| 132 |
+
</label>
|
| 133 |
+
</div>
|
| 134 |
+
</div>
|
| 135 |
+
|
| 136 |
+
<!-- 翻訳オプション -->
|
| 137 |
+
<div class="flex flex-col gap-2 border border-gray-200 rounded-lg px-4 py-3">
|
| 138 |
+
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wide">翻訳(オプション)</p>
|
| 139 |
+
<div class="flex items-center gap-3 text-sm">
|
| 140 |
+
<label class="flex items-center gap-1.5 cursor-pointer">
|
| 141 |
+
<input id="translate_on" type="checkbox" class="accent-cyan-500">
|
| 142 |
+
<span class="font-medium">翻訳する</span>
|
| 143 |
+
</label>
|
| 144 |
+
<input id="translate_trg_lang"
|
| 145 |
+
type="text"
|
| 146 |
+
placeholder="英語・日本語・中国語..."
|
| 147 |
+
disabled
|
| 148 |
+
class="border border-gray-200 rounded-lg px-2 py-1.5 text-xs w-28
|
| 149 |
+
disabled:bg-gray-50 disabled:text-gray-300 disabled:cursor-not-allowed
|
| 150 |
+
focus:outline-none focus:border-cyan-400 transition-colors">
|
| 151 |
+
</div>
|
| 152 |
+
</div>
|
| 153 |
+
|
| 154 |
+
</div>
|
| 155 |
+
|
| 156 |
+
<!-- アクションボタン -->
|
| 157 |
+
<div class="flex gap-3 px-4 pb-5">
|
| 158 |
+
<button id="start_btn"
|
| 159 |
+
class="flex items-center gap-2 px-5 py-2.5 bg-cyan-600 hover:bg-cyan-700 active:bg-cyan-800
|
| 160 |
+
text-white rounded-lg font-semibold text-sm transition-colors shadow-sm
|
| 161 |
+
disabled:opacity-40 disabled:cursor-not-allowed">
|
| 162 |
+
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 163 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 164 |
+
d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
|
| 165 |
+
<path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
| 166 |
+
</svg>
|
| 167 |
+
書き出し開始
|
| 168 |
+
</button>
|
| 169 |
+
<button id="clear_btn"
|
| 170 |
+
class="flex items-center gap-2 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 active:bg-gray-300
|
| 171 |
+
text-gray-600 rounded-lg font-semibold text-sm transition-colors">
|
| 172 |
+
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 173 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 174 |
+
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
| 175 |
+
</svg>
|
| 176 |
+
クリア
|
| 177 |
+
</button>
|
| 178 |
+
</div>
|
| 179 |
+
|
| 180 |
+
<!-- ステータスパネル(ロード中/処理中) -->
|
| 181 |
+
<div id="status-panel" class="hidden items-center gap-3 px-4 py-3 mx-4 mb-3 rounded-xl border transition-all duration-300">
|
| 182 |
+
<svg id="status-spin" class="w-5 h-5 shrink-0 animate-spin" fill="none" viewBox="0 0 24 24">
|
| 183 |
+
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
| 184 |
+
<path class="opacity-75" fill="currentColor"
|
| 185 |
+
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
|
| 186 |
+
</path>
|
| 187 |
+
</svg>
|
| 188 |
+
<div class="min-w-0">
|
| 189 |
+
<p id="status-title" class="text-sm font-semibold leading-tight"></p>
|
| 190 |
+
<p id="status-detail" class="text-xs mt-0.5 leading-tight text-gray-500"></p>
|
| 191 |
+
</div>
|
| 192 |
+
</div>
|
| 193 |
+
|
| 194 |
+
<!-- 情報バー(言語推定結果・完了など) -->
|
| 195 |
+
<div id="info-bar"
|
| 196 |
+
class="hidden px-4 py-2 mx-4 mb-2 bg-cyan-50 rounded-lg border border-cyan-100
|
| 197 |
+
text-sm text-cyan-800 font-medium">
|
| 198 |
+
</div>
|
| 199 |
+
|
| 200 |
+
<!-- 結果コンテナ -->
|
| 201 |
+
<div id="result-container"
|
| 202 |
+
class="relative min-h-[160px] max-h-[52vh] mx-4 mb-2
|
| 203 |
+
border border-gray-200 rounded-xl overflow-y-auto">
|
| 204 |
+
<div id="result-placeholder"
|
| 205 |
+
class="absolute inset-0 flex items-center justify-center text-gray-300 text-sm select-none pointer-events-none">
|
| 206 |
+
文字起こし結果がここに表示されます
|
| 207 |
+
</div>
|
| 208 |
+
</div>
|
| 209 |
+
|
| 210 |
+
<!-- ツールバー(文字数・コピー・DL) -->
|
| 211 |
+
<div id="result-toolbar" class="hidden items-center gap-3 px-4 pb-5 flex-wrap">
|
| 212 |
+
<span id="char-count" class="text-xs text-gray-400">0 文字</span>
|
| 213 |
+
<div class="flex-1"></div>
|
| 214 |
+
<button id="copy_btn"
|
| 215 |
+
class="flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 hover:bg-gray-200
|
| 216 |
+
text-gray-600 rounded-lg text-xs font-medium transition-colors">
|
| 217 |
+
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 218 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 219 |
+
d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
|
| 220 |
+
</svg>
|
| 221 |
+
テキストのみコピー
|
| 222 |
+
</button>
|
| 223 |
+
<button id="download_btn"
|
| 224 |
+
class="flex items-center gap-1.5 px-3 py-1.5 bg-cyan-600 hover:bg-cyan-700
|
| 225 |
+
text-white rounded-lg text-xs font-medium transition-colors">
|
| 226 |
+
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
| 227 |
+
<path stroke-linecap="round" stroke-linejoin="round"
|
| 228 |
+
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
| 229 |
+
</svg>
|
| 230 |
+
ダウンロード (.txt)
|
| 231 |
+
</button>
|
| 232 |
+
</div>
|
| 233 |
+
|
| 234 |
+
</div><!-- /.whisper-card -->
|
| 235 |
+
|
| 236 |
+
<!-- 注釈 -->
|
| 237 |
+
<p class="mt-4 text-xs text-gray-400 text-center leading-relaxed">
|
| 238 |
+
※ Small: 高速・軽量 / Large: 高精度(初回ロードに数分かかる場合があります)<br>
|
| 239 |
+
タイムスタンプあり: 時刻付きで書き出し(whisper_text_time.txt) / タイムスタンプなし: テキストのみ(whisper_only_text.txt)<br>
|
| 240 |
+
翻訳オプションは LFM 2.5 (ONNX) を使用します。翻訳先は「英語」「中国語」などの言語名で入力してください。
|
| 241 |
+
</p>
|
| 242 |
+
|
| 243 |
+
</main>
|
| 244 |
+
|
| 245 |
+
<script>
|
| 246 |
+
// ─── DOM 要素 ────────────────────────────────────────────────
|
| 247 |
+
const whisperCard = document.getElementById('whisper-card');
|
| 248 |
+
const spinner = document.getElementById('spinner');
|
| 249 |
+
const spinnerSvg = document.getElementById('spinner-svg');
|
| 250 |
+
const statusPanel = document.getElementById('status-panel');
|
| 251 |
+
const statusSpin = document.getElementById('status-spin');
|
| 252 |
+
const statusTitle = document.getElementById('status-title');
|
| 253 |
+
const statusDetail = document.getElementById('status-detail');
|
| 254 |
+
const infoBar = document.getElementById('info-bar');
|
| 255 |
+
const resultContainer = document.getElementById('result-container');
|
| 256 |
+
const resultPlaceholder = document.getElementById('result-placeholder');
|
| 257 |
+
const resultToolbar = document.getElementById('result-toolbar');
|
| 258 |
+
const charCountEl = document.getElementById('char-count');
|
| 259 |
+
const fileInput = document.getElementById('file_input');
|
| 260 |
+
const dropArea = document.getElementById('drop-area');
|
| 261 |
+
const dropPlaceholder = document.getElementById('drop-placeholder');
|
| 262 |
+
const fileInfoDiv = document.getElementById('file-info');
|
| 263 |
+
const fileNameEl = document.getElementById('file-name');
|
| 264 |
+
const fileSizeEl = document.getElementById('file-size');
|
| 265 |
+
const startBtn = document.getElementById('start_btn');
|
| 266 |
+
const clearBtn = document.getElementById('clear_btn');
|
| 267 |
+
const translateOn = document.getElementById('translate_on');
|
| 268 |
+
const translateLang = document.getElementById('translate_trg_lang');
|
| 269 |
+
const copyBtn = document.getElementById('copy_btn');
|
| 270 |
+
const downloadBtn = document.getElementById('download_btn');
|
| 271 |
+
|
| 272 |
+
let isProcessing = false;
|
| 273 |
+
let allText = []; // 全テキスト(コピー・DL 用)
|
| 274 |
+
|
| 275 |
+
// ─── モデル選択で枠色・スピナー色変更 ──────────────────────
|
| 276 |
+
document.querySelectorAll('input[name="model"]').forEach(radio => {
|
| 277 |
+
radio.addEventListener('change', function () {
|
| 278 |
+
if (this.value === 'Large') {
|
| 279 |
+
whisperCard.classList.add('large-mode');
|
| 280 |
+
spinnerSvg.classList.replace('text-cyan-500', 'text-red-400');
|
| 281 |
+
} else {
|
| 282 |
+
whisperCard.classList.remove('large-mode');
|
| 283 |
+
spinnerSvg.classList.replace('text-red-400', 'text-cyan-500');
|
| 284 |
+
}
|
| 285 |
+
});
|
| 286 |
+
});
|
| 287 |
+
|
| 288 |
+
// ─── 翻訳チェックボックスで入力欄を有効化 ──────────────────
|
| 289 |
+
translateOn.addEventListener('change', function () {
|
| 290 |
+
translateLang.disabled = !this.checked;
|
| 291 |
+
if (this.checked) translateLang.focus();
|
| 292 |
+
});
|
| 293 |
+
|
| 294 |
+
// ─── ステータスパネル ────────────────────────────────────────
|
| 295 |
+
function showStatus(type, message, detail) {
|
| 296 |
+
if (type === 'loading') {
|
| 297 |
+
statusPanel.className = 'flex items-center gap-3 px-4 py-3 mx-4 mb-3 rounded-xl border border-amber-200 bg-amber-50';
|
| 298 |
+
statusTitle.className = 'text-sm font-semibold leading-tight text-amber-800';
|
| 299 |
+
statusSpin.classList.remove('text-indigo-500');
|
| 300 |
+
statusSpin.classList.add('text-amber-500');
|
| 301 |
+
} else {
|
| 302 |
+
statusPanel.className = 'flex items-center gap-3 px-4 py-3 mx-4 mb-3 rounded-xl border border-indigo-200 bg-indigo-50';
|
| 303 |
+
statusTitle.className = 'text-sm font-semibold leading-tight text-indigo-800';
|
| 304 |
+
statusSpin.classList.remove('text-amber-500');
|
| 305 |
+
statusSpin.classList.add('text-indigo-500');
|
| 306 |
+
}
|
| 307 |
+
statusTitle.textContent = message;
|
| 308 |
+
statusDetail.textContent = detail || '';
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
function hideStatus() {
|
| 312 |
+
statusPanel.classList.add('hidden');
|
| 313 |
+
statusPanel.classList.remove('flex');
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
// ─── ファイルサイズ表示 ─────────────────────────────────────
|
| 317 |
+
function formatSize(bytes) {
|
| 318 |
+
if (bytes < 1024) return `${bytes} B`;
|
| 319 |
+
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
|
| 320 |
+
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
// ─── ファイルアップロード ────────────────────────────────────
|
| 324 |
+
async function uploadFile(file) {
|
| 325 |
+
fileNameEl.textContent = file.name;
|
| 326 |
+
fileSizeEl.textContent = formatSize(file.size);
|
| 327 |
+
dropPlaceholder.classList.add('hidden');
|
| 328 |
+
fileInfoDiv.classList.remove('hidden');
|
| 329 |
+
fileInfoDiv.classList.add('flex');
|
| 330 |
+
|
| 331 |
+
const formData = new FormData();
|
| 332 |
+
formData.append('file', file);
|
| 333 |
+
await fetch('/whisper/upload', { method: 'POST', body: formData });
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
fileInput.addEventListener('change', async function () {
|
| 337 |
+
if (this.files[0]) await uploadFile(this.files[0]);
|
| 338 |
+
});
|
| 339 |
+
|
| 340 |
+
// ─── ドラッグ&ドロップ ──────────────────────────────────────
|
| 341 |
+
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(ev =>
|
| 342 |
+
dropArea.addEventListener(ev, e => { e.preventDefault(); e.stopPropagation(); })
|
| 343 |
+
);
|
| 344 |
+
dropArea.addEventListener('dragenter', () => dropArea.classList.add('drag-over'));
|
| 345 |
+
dropArea.addEventListener('dragover', () => dropArea.classList.add('drag-over'));
|
| 346 |
+
dropArea.addEventListener('dragleave', () => dropArea.classList.remove('drag-over'));
|
| 347 |
+
dropArea.addEventListener('drop', async e => {
|
| 348 |
+
dropArea.classList.remove('drag-over');
|
| 349 |
+
const file = e.dataTransfer.files[0];
|
| 350 |
+
if (file) { fileInput.files = e.dataTransfer.files; await uploadFile(file); }
|
| 351 |
+
});
|
| 352 |
+
|
| 353 |
+
// ─── 情報バー ────────────────────────────────────────────────
|
| 354 |
+
function showInfo(text, isError = false) {
|
| 355 |
+
infoBar.textContent = text;
|
| 356 |
+
infoBar.className = isError
|
| 357 |
+
? 'flex px-4 py-2 mx-4 mb-2 bg-red-50 rounded-lg border border-red-100 text-sm text-red-700 font-medium'
|
| 358 |
+
: 'flex px-4 py-2 mx-4 mb-2 bg-cyan-50 rounded-lg border border-cyan-100 text-sm text-cyan-800 font-medium';
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
// ─── 結果行追加 ─────────────────────────────────────────────
|
| 362 |
+
function addSegmentRow(timeLabel, text) {
|
| 363 |
+
resultPlaceholder.classList.add('hidden');
|
| 364 |
+
resultToolbar.classList.remove('hidden');
|
| 365 |
+
resultToolbar.classList.add('flex');
|
| 366 |
+
|
| 367 |
+
const row = document.createElement('div');
|
| 368 |
+
row.className = 'result-row flex gap-0 border-b border-gray-100 last:border-0';
|
| 369 |
+
|
| 370 |
+
if (timeLabel) {
|
| 371 |
+
row.innerHTML = `
|
| 372 |
+
<div class="w-36 shrink-0 px-3 py-2 text-xs text-gray-400 select-none
|
| 373 |
+
border-r border-gray-100 font-mono leading-relaxed">${timeLabel}</div>
|
| 374 |
+
<div class="flex-1 px-3 py-2 text-sm text-gray-800 select-text
|
| 375 |
+
cursor-pointer leading-relaxed">${text}</div>`;
|
| 376 |
+
} else {
|
| 377 |
+
row.innerHTML = `
|
| 378 |
+
<div class="flex-1 px-4 py-2 text-sm text-gray-800 select-text leading-relaxed">${text}</div>`;
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
resultContainer.appendChild(row);
|
| 382 |
+
resultContainer.scrollTop = resultContainer.scrollHeight;
|
| 383 |
+
allText.push(text);
|
| 384 |
+
charCountEl.textContent = `${allText.join('').replace(/\s/g, '').length} 文字`;
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
// ─── 書き出し開始 ────────────────────────────────────────────
|
| 388 |
+
startBtn.addEventListener('click', async function () {
|
| 389 |
+
if (isProcessing) return;
|
| 390 |
+
isProcessing = true;
|
| 391 |
+
startBtn.disabled = true;
|
| 392 |
+
spinner.classList.remove('hidden');
|
| 393 |
+
|
| 394 |
+
const modelType = document.querySelector('input[name="model"]:checked').value;
|
| 395 |
+
const modeType = document.querySelector('input[name="mode"]:checked').value;
|
| 396 |
+
const trgLang = translateOn.checked ? translateLang.value.trim() : '';
|
| 397 |
+
|
| 398 |
+
const response = await fetch('/whisper/process', {
|
| 399 |
+
method: 'POST',
|
| 400 |
+
headers: { 'Content-Type': 'application/json' },
|
| 401 |
+
body: JSON.stringify({ model_type: modelType, mode_type: modeType, trg_lang: trgLang }),
|
| 402 |
+
});
|
| 403 |
+
|
| 404 |
+
const reader = response.body.getReader();
|
| 405 |
+
const decoder = new TextDecoder();
|
| 406 |
+
let buffer = '';
|
| 407 |
+
|
| 408 |
+
async function readStream() {
|
| 409 |
+
const { done, value } = await reader.read();
|
| 410 |
+
if (done) {
|
| 411 |
+
isProcessing = false;
|
| 412 |
+
startBtn.disabled = false;
|
| 413 |
+
spinner.classList.add('hidden');
|
| 414 |
+
hideStatus();
|
| 415 |
+
return;
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
buffer += decoder.decode(value, { stream: true });
|
| 419 |
+
const lines = buffer.split('\n');
|
| 420 |
+
buffer = lines.pop();
|
| 421 |
+
|
| 422 |
+
for (const line of lines) {
|
| 423 |
+
if (!line.startsWith('data: ')) continue;
|
| 424 |
+
let data;
|
| 425 |
+
try { data = JSON.parse(line.slice(6)); } catch { continue; }
|
| 426 |
+
|
| 427 |
+
if (data.status) {
|
| 428 |
+
showStatus(data.status, data.message, data.detail);
|
| 429 |
+
} else if (data.type === 'info') {
|
| 430 |
+
showInfo(data.text);
|
| 431 |
+
} else if (data.type === 'segment') {
|
| 432 |
+
addSegmentRow(data.time || '', data.text);
|
| 433 |
+
} else if (data.error) {
|
| 434 |
+
hideStatus();
|
| 435 |
+
showInfo(`エラー: ${data.error}`, true);
|
| 436 |
+
isProcessing = false;
|
| 437 |
+
startBtn.disabled = false;
|
| 438 |
+
spinner.classList.add('hidden');
|
| 439 |
+
return;
|
| 440 |
+
} else if (data.done) {
|
| 441 |
+
hideStatus();
|
| 442 |
+
const elapsed = data.elapsed ? ` (${data.elapsed} 秒)` : '';
|
| 443 |
+
showInfo(`✓ 書き出し完了${elapsed}`);
|
| 444 |
+
}
|
| 445 |
+
}
|
| 446 |
+
await readStream();
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
await readStream();
|
| 450 |
+
});
|
| 451 |
+
|
| 452 |
+
// ─── クリア ──────────────────────────────────────────────────
|
| 453 |
+
clearBtn.addEventListener('click', function () {
|
| 454 |
+
resultContainer.innerHTML = '';
|
| 455 |
+
resultContainer.appendChild(resultPlaceholder);
|
| 456 |
+
resultPlaceholder.classList.remove('hidden');
|
| 457 |
+
resultToolbar.classList.add('hidden');
|
| 458 |
+
resultToolbar.classList.remove('flex');
|
| 459 |
+
infoBar.classList.add('hidden');
|
| 460 |
+
infoBar.classList.remove('flex');
|
| 461 |
+
hideStatus();
|
| 462 |
+
allText = [];
|
| 463 |
+
charCountEl.textContent = '0 文字';
|
| 464 |
+
});
|
| 465 |
+
|
| 466 |
+
// ─── テキストのみコピー ─────────────────────────────────────
|
| 467 |
+
copyBtn.addEventListener('click', function () {
|
| 468 |
+
const texts = Array.from(
|
| 469 |
+
document.querySelectorAll('#result-container .result-row div:last-child')
|
| 470 |
+
).map(el => el.textContent.trim()).filter(Boolean);
|
| 471 |
+
|
| 472 |
+
navigator.clipboard.writeText(texts.join('\n')).then(() => {
|
| 473 |
+
const orig = copyBtn.innerHTML;
|
| 474 |
+
copyBtn.textContent = '✓ コピー完了';
|
| 475 |
+
setTimeout(() => { copyBtn.innerHTML = orig; }, 1500);
|
| 476 |
+
});
|
| 477 |
+
});
|
| 478 |
+
|
| 479 |
+
// ─── ダウンロード ────────────────────────────────────────────
|
| 480 |
+
downloadBtn.addEventListener('click', function () {
|
| 481 |
+
const modeType = document.querySelector('input[name="mode"]:checked').value;
|
| 482 |
+
const type = modeType === 'タイムスタンプあり' ? 'text_time' : 'text_only';
|
| 483 |
+
window.location.href = `/whisper/download?type=${type}`;
|
| 484 |
+
});
|
| 485 |
+
</script>
|
| 486 |
+
{% endblock %}
|
MM_tools/app/shared/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# shared パッケージ
|
MM_tools/app/shared/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (156 Bytes). View file
|
|
|
MM_tools/app/shared/__pycache__/models.cpython-314.pyc
ADDED
|
Binary file (8 kB). View file
|
|
|
MM_tools/app/shared/__pycache__/utils.cpython-314.pyc
ADDED
|
Binary file (2.08 kB). View file
|
|
|
MM_tools/app/shared/models.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
遅延ロード対応の共有モデル管理モジュール。
|
| 3 |
+
|
| 4 |
+
各モデルは初回呼び出し時にのみロードされる(遅延初期化パターン)。
|
| 5 |
+
スレッドセーフのために各モデルに専用ロックを用意している。
|
| 6 |
+
モデルパスやデバイス設定は config.py で一元管理する。
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
import threading
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# config.py のある ROOT を sys.path に追加してインポートを保証
|
| 14 |
+
_ROOT = Path(__file__).parent.parent.parent
|
| 15 |
+
if str(_ROOT) not in sys.path:
|
| 16 |
+
sys.path.insert(0, str(_ROOT))
|
| 17 |
+
|
| 18 |
+
from config import (
|
| 19 |
+
GLM_OCR_PATH,
|
| 20 |
+
LFM_MODEL_PATH,
|
| 21 |
+
QWEN_MODEL_PATH,
|
| 22 |
+
WHISPER_SMALL_ID,
|
| 23 |
+
WHISPER_LARGE_ID,
|
| 24 |
+
DEVICE,
|
| 25 |
+
WHISPER_COMPUTE_TYPE,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ── GLM-OCR モデル(ocr ブループリント用) ─────────────────────────────────
|
| 30 |
+
|
| 31 |
+
_glm_processor = None
|
| 32 |
+
_glm_model = None
|
| 33 |
+
_glm_lock = threading.Lock()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def is_glm_loaded() -> bool:
|
| 37 |
+
"""GLM-OCR モデルがロード済みかどうかを返す(ロックなし)。"""
|
| 38 |
+
return _glm_model is not None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_glm_model():
|
| 42 |
+
"""
|
| 43 |
+
GLM-OCR モデルをローカルから遅延ロードして返す。
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
tuple[AutoProcessor, AutoModelForImageTextToText]: (processor, model)
|
| 47 |
+
|
| 48 |
+
Raises:
|
| 49 |
+
Exception: モデルのロードに失敗した場合
|
| 50 |
+
"""
|
| 51 |
+
global _glm_processor, _glm_model
|
| 52 |
+
with _glm_lock:
|
| 53 |
+
if _glm_model is None:
|
| 54 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 55 |
+
|
| 56 |
+
model_path = str(GLM_OCR_PATH)
|
| 57 |
+
print(f"[OCR] GLM モデルをロード中: {model_path}")
|
| 58 |
+
_glm_processor = AutoProcessor.from_pretrained(model_path)
|
| 59 |
+
_glm_model = AutoModelForImageTextToText.from_pretrained(
|
| 60 |
+
pretrained_model_name_or_path=model_path,
|
| 61 |
+
torch_dtype="auto",
|
| 62 |
+
device_map=DEVICE,
|
| 63 |
+
)
|
| 64 |
+
print("[OCR] GLM モデルのロード完了")
|
| 65 |
+
return _glm_processor, _glm_model
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ── LFM 2.5 翻訳モデル(translation / ocr / whisper ブループリント共用) ──
|
| 69 |
+
|
| 70 |
+
_lfm = None
|
| 71 |
+
_lfm_init_lock = threading.Lock() # 初期化専用ロック(二重初期化防止)
|
| 72 |
+
_lfm_infer_lock = threading.Lock() # 推論専用ロック(全ブループリント共有)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def is_lfm_loaded() -> bool:
|
| 76 |
+
"""LFM 翻訳モデルがロード済みかどうかを返す(ロックなし)。"""
|
| 77 |
+
return _lfm is not None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_lfm():
|
| 81 |
+
"""
|
| 82 |
+
LFM 2.5 (ONNX) 翻訳モデルを遅延ロードして返す。
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
LFMInference: LFM 推論インスタンス
|
| 86 |
+
|
| 87 |
+
Raises:
|
| 88 |
+
Exception: モデルのロードに失敗した場合
|
| 89 |
+
"""
|
| 90 |
+
global _lfm
|
| 91 |
+
with _lfm_init_lock:
|
| 92 |
+
if _lfm is None:
|
| 93 |
+
from lfm25_run import LFMInference
|
| 94 |
+
|
| 95 |
+
model_path = str(LFM_MODEL_PATH)
|
| 96 |
+
print(f"[Translation] LFM モデルをロード中: {model_path}")
|
| 97 |
+
_lfm = LFMInference(model_path)
|
| 98 |
+
print("[Translation] LFM モデルのロード完了")
|
| 99 |
+
return _lfm
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_lfm_lock() -> threading.Lock:
|
| 103 |
+
"""
|
| 104 |
+
LFM 推論用の共有排他ロックを返す。
|
| 105 |
+
|
| 106 |
+
全ブループリントでこのロックを取得してから推論を実行すること。
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
threading.Lock: 推論用ロック
|
| 110 |
+
"""
|
| 111 |
+
return _lfm_infer_lock
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ── Qwen3-VL モデル(ledger ブループリント用) ─────────────────────────────
|
| 115 |
+
|
| 116 |
+
_qwen_processor = None
|
| 117 |
+
_qwen_model = None
|
| 118 |
+
_qwen_lock = threading.Lock()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_qwen_model():
|
| 122 |
+
"""
|
| 123 |
+
Qwen3-VL-2B モデルをローカルから遅延ロードして返す。
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
tuple[AutoProcessor, AutoModelForImageTextToText]: (processor, model)
|
| 127 |
+
|
| 128 |
+
Raises:
|
| 129 |
+
Exception: モデルのロードに失敗した場合
|
| 130 |
+
"""
|
| 131 |
+
global _qwen_processor, _qwen_model
|
| 132 |
+
with _qwen_lock:
|
| 133 |
+
if _qwen_model is None:
|
| 134 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 135 |
+
|
| 136 |
+
model_path = str(QWEN_MODEL_PATH)
|
| 137 |
+
print(f"[Ledger] Qwen モデルをロード中: {model_path}")
|
| 138 |
+
_qwen_processor = AutoProcessor.from_pretrained(
|
| 139 |
+
model_path,
|
| 140 |
+
min_pixels=256 * 28 * 28,
|
| 141 |
+
max_pixels=768 * 28 * 28,
|
| 142 |
+
)
|
| 143 |
+
_qwen_model = AutoModelForImageTextToText.from_pretrained(
|
| 144 |
+
model_path,
|
| 145 |
+
torch_dtype="auto",
|
| 146 |
+
device_map=DEVICE,
|
| 147 |
+
low_cpu_mem_usage=True,
|
| 148 |
+
)
|
| 149 |
+
_qwen_model.eval()
|
| 150 |
+
print("[Ledger] Qwen モデルのロード完了")
|
| 151 |
+
return _qwen_processor, _qwen_model
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# ── Whisper 音声認識モデル(whisper ブループリント用) ────────────────────────
|
| 155 |
+
|
| 156 |
+
_whisper_small = None
|
| 157 |
+
_whisper_small_lock = threading.Lock()
|
| 158 |
+
_whisper_large = None
|
| 159 |
+
_whisper_large_lock = threading.Lock()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def is_whisper_small_loaded() -> bool:
|
| 163 |
+
"""Whisper Small モデルがロード済みかどうかを返す(ロックなし)。"""
|
| 164 |
+
return _whisper_small is not None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def is_whisper_large_loaded() -> bool:
|
| 168 |
+
"""Whisper Large モデルがロード済みかどうかを返す(ロックなし)。"""
|
| 169 |
+
return _whisper_large is not None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_whisper_small():
|
| 173 |
+
"""
|
| 174 |
+
Whisper Small モデルを遅延ロードして返す。
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
WhisperModel: faster-whisper Small モデルインスタンス
|
| 178 |
+
"""
|
| 179 |
+
global _whisper_small
|
| 180 |
+
with _whisper_small_lock:
|
| 181 |
+
if _whisper_small is None:
|
| 182 |
+
from faster_whisper import WhisperModel
|
| 183 |
+
print(f"[Whisper] Small モデルをロード中: {WHISPER_SMALL_ID}")
|
| 184 |
+
_whisper_small = WhisperModel(
|
| 185 |
+
WHISPER_SMALL_ID,
|
| 186 |
+
device=DEVICE,
|
| 187 |
+
compute_type=WHISPER_COMPUTE_TYPE,
|
| 188 |
+
)
|
| 189 |
+
print("[Whisper] Small モデルのロード完了")
|
| 190 |
+
return _whisper_small
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def get_whisper_large():
|
| 194 |
+
"""
|
| 195 |
+
Whisper Large-v3-turbo モデルを遅延ロードして返す。
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
WhisperModel: faster-whisper Large-v3-turbo モデルインスタンス
|
| 199 |
+
"""
|
| 200 |
+
global _whisper_large
|
| 201 |
+
with _whisper_large_lock:
|
| 202 |
+
if _whisper_large is None:
|
| 203 |
+
from faster_whisper import WhisperModel
|
| 204 |
+
print(f"[Whisper] Large モデルをロード中: {WHISPER_LARGE_ID}")
|
| 205 |
+
_whisper_large = WhisperModel(
|
| 206 |
+
WHISPER_LARGE_ID,
|
| 207 |
+
device=DEVICE,
|
| 208 |
+
compute_type=WHISPER_COMPUTE_TYPE,
|
| 209 |
+
)
|
| 210 |
+
print("[Whisper] Large モデルのロード完了")
|
| 211 |
+
return _whisper_large
|
MM_tools/app/shared/utils.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""共通ユーティリティ関数。"""
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import base64
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def sse_event(data: dict) -> str:
|
| 11 |
+
"""
|
| 12 |
+
辞書を SSE フォーマット文字列に変換する。
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
data: JSON シリアライズ可能な辞書
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
str: "data: {...}\\n\\n" 形式の SSE 文字列
|
| 19 |
+
"""
|
| 20 |
+
return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def resize_image_to_base64(image: Image.Image, max_size: int = 512) -> str:
|
| 24 |
+
"""
|
| 25 |
+
PIL 画像をリサイズして Base64 エンコード済み JPEG 文字列を返す。
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
image: PIL.Image オブジェクト
|
| 29 |
+
max_size: 長辺の最大ピクセル数
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
str: Base64 エンコード済み文字列(JPEG 形式)
|
| 33 |
+
"""
|
| 34 |
+
img = image.copy()
|
| 35 |
+
img.thumbnail((max_size, max_size), Image.LANCZOS)
|
| 36 |
+
buffer = io.BytesIO()
|
| 37 |
+
img.save(buffer, format="JPEG", quality=85)
|
| 38 |
+
buffer.seek(0)
|
| 39 |
+
return base64.b64encode(buffer.read()).decode("utf-8")
|
MM_tools/app/static/Flag_of_Japan_Customs.svg.png
ADDED
|
Git LFS Details
|
MM_tools/app/static/HP1.png
ADDED
|
Git LFS Details
|
MM_tools/app/static/exports/whisper_minutes.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
サーチサーチングサーチングカットサーチングカット切サーチングカット切削サーチングカット切削油サーチングカット切削油はサーチングカット切削油は、サーチングカット切削油は、被サーチングカット切削油は、被作サーチングカット切削油は、被作性のサーチングカット切削油は、被作性の悪いサーチングカット切削油は、被作性の悪いステンレスサーチングカット切削油は、被作性の悪いステンレス、サーチングカット切削油は、被作性の悪いステンレス、シサーチングカット切削油は、被作性の悪いステンレス、シタンサーチングカット切削油は、被作性の悪いステンレス、シタン、サーチングカット切削油は、被作性の悪いステンレス、シタン、コサーチングカット切削油は、被作性の悪いステンレス、シタン、コバサーチングカット切削油は、被作性の悪いステンレス、シタン、コバールサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネルサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といったサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザーサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にごサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただきサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度をサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視するサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、イン��ネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいた���き、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などのサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油としてサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございますサーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございます。サーチングカット切削油は、被作性の悪いステンレス、シタン、コバール、インコネル、銅といった軟削材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございます。
|
MM_tools/app/static/exports/whisper_only_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Searching cutting cutting oil is a challenging material processing oil for non-stick steel, shank, cobalt, iridium, copper, and other difficult-to-machine materials. We have a proven track record in precision machining for automotive parts, medical devices, hygiene-related components, aerospace parts, and weak-electricity-sensitive components. (原文: サーチングカット切削油は、非作成の悪いステンレス、シタン、コバール、インコネル、銅といった難作材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございます。)
|
MM_tools/app/static/exports/whisper_text_time.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[1s → 26s] サーチングカット切削油は、非作成の悪いステンレス、シタン、コバール、インコネル、銅といった難作材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございます。
|