showeed commited on
Commit
43e2c99
·
verified ·
1 Parent(s): 7045443

Upload 85 files

Browse files
MM_tools/__pycache__/config.cpython-314.pyc ADDED
Binary file (1.26 kB). View file
 
MM_tools/app/blueprints/ledger/__pycache__/routes.cpython-314.pyc CHANGED
Binary files a/MM_tools/app/blueprints/ledger/__pycache__/routes.cpython-314.pyc and b/MM_tools/app/blueprints/ledger/__pycache__/routes.cpython-314.pyc differ
 
MM_tools/app/blueprints/ledger/routes.py CHANGED
@@ -18,7 +18,7 @@ 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"
@@ -28,29 +28,19 @@ OUTPUT_DIR.mkdir(exist_ok=True)
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("/")
@@ -80,25 +70,27 @@ def process():
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
  # ── モデルロード ──
@@ -257,6 +249,7 @@ def _try_numeric(value: str):
257
  def _save_to_excel(data: dict, output_path: Path) -> None:
258
  """
259
  JSON データを整形した Excel ファイルに書き出す。
 
260
 
261
  Args:
262
  data: 抽出済み JSON 辞書 (title, tables キーを持つ)
@@ -269,25 +262,35 @@ def _save_to_excel(data: dict, output_path: Path) -> None:
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")
@@ -295,6 +298,7 @@ def _save_to_excel(data: dict, output_path: Path) -> None:
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):
@@ -307,20 +311,22 @@ def _save_to_excel(data: dict, output_path: Path) -> None:
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
 
 
18
 
19
  from . import ledger_bp
20
  from app.shared.models import get_qwen_model
21
+ from app.shared.utils import sse_event, open_image_or_pdf
22
 
23
  # 出力先ディレクトリ(プロジェクトルートの output/)
24
  OUTPUT_DIR = Path(__file__).parent.parent.parent.parent / "output"
 
28
  _model_lock = threading.Lock()
29
 
30
  # 表データ抽出プロンプト
31
+ OCR_PROMPT = """You are a table OCR assistant. Extract all tabular data from this image and output ONLY valid JSON. No explanation, no markdown, no code fences — just raw JSON starting with { and ending with }.
32
+
33
+ Output format:
34
+ {"title": "table title or null", "tables": [{"headers": ["col1", "col2"], "rows": [["val1", "val2"]]}]}
35
+
36
+ Rules:
37
+ - Output ONLY the JSON object. Do not write anything before or after it.
38
+ - Use half-width digits for numbers.
39
+ - Keep dates exactly as written.
40
+ - Use "???" for unreadable characters.
41
+ - If multiple tables exist, include all in the "tables" array.
42
+ - If no title is visible, set "title" to null.
43
+ - Every row must have the same number of cells as headers."""
 
 
 
 
 
 
 
 
 
 
44
 
45
 
46
  @ledger_bp.route("/")
 
70
  # SSEジェネレータの遅延実行時にリクエストストリームが閉じられる問題を防ぐため、
71
  # ここでバイト列として先読みしておく
72
  image_bytes: bytes | None = None
73
+ image_filename: str = ""
74
  if image_file and image_file.filename:
75
  image_bytes = image_file.read()
76
+ image_filename = image_file.filename # PDF 判定用
77
 
78
  def generate():
79
  with _model_lock:
80
  try:
81
+ # ── 画像読み込み(PDF は1ページ目を変換)──
82
+ yield sse_event({"progress": "ファイルを読み込み中...", "step": 1})
83
 
84
  if image_bytes:
85
+ image = open_image_or_pdf(image_bytes, image_filename)
86
  elif image_path_str:
87
  p = Path(image_path_str)
88
  if not p.exists():
89
  yield sse_event({"error": f"ファイルが見つかりません: {image_path_str}"})
90
  return
91
+ image = open_image_or_pdf(p.read_bytes(), p.name)
92
  else:
93
+ yield sse_event({"error": "画像または PDF をアップロードするか、パスを入力してください。"})
94
  return
95
 
96
  # ── モデルロード ──
 
249
  def _save_to_excel(data: dict, output_path: Path) -> None:
250
  """
251
  JSON データを整形した Excel ファイルに書き出す。
252
+ 複数テーブルがある場合は 1 シートに縦に並べ、テーブル間に 1 行空白を入れる。
253
 
254
  Args:
255
  data: 抽出済み JSON 辞書 (title, tables キーを持つ)
 
262
  ROW_FILL_ODD = PatternFill(start_color="DCE6F1", end_color="DCE6F1", fill_type="solid")
263
 
264
  wb = openpyxl.Workbook()
265
+ ws = wb.active
266
+ ws.title = "帳簿"
267
+
268
  book_title = data.get("title")
269
  tables = data.get("tables", [])
270
 
271
  if not tables:
272
  raise ValueError("tables キーが空です。")
273
 
274
+ row_ptr = 1
275
+ first_header_row = None # freeze_panes 用に最初のヘッダ行を記録
 
 
276
 
277
+ # タイトル行(あれば)
278
+ if book_title:
279
+ title_cell = ws.cell(row=row_ptr, column=1, value=book_title)
280
+ title_cell.font = Font(bold=True, size=14)
281
+ row_ptr += 2
282
+
283
+ for idx, table in enumerate(tables):
284
+ # テーブル間の空白行(2つ目以降)
285
+ if idx > 0:
286
+ row_ptr += 1 # 1行空ける
287
 
288
  headers = table.get("headers", [])
289
  rows = table.get("rows", [])
290
 
291
+ # ヘッダ行
292
+ if first_header_row is None:
293
+ first_header_row = row_ptr
294
  for col_idx, header in enumerate(headers, start=1):
295
  cell = ws.cell(row=row_ptr, column=col_idx, value=header)
296
  cell.font = Font(bold=True, color="FFFFFF")
 
298
  cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
299
  row_ptr += 1
300
 
301
+ # データ行
302
  for row_num, row_data in enumerate(rows):
303
  fill = ROW_FILL_ODD if row_num % 2 == 0 else None
304
  for col_idx, raw_value in enumerate(row_data, start=1):
 
311
  cell.alignment = Alignment(horizontal="right", vertical="center")
312
  row_ptr += 1
313
 
314
+ # 行高・列幅の自動調整
315
+ for row in ws.iter_rows():
316
+ ws.row_dimensions[row[0].row].height = 18
317
+
318
+ for col in ws.columns:
319
+ max_len = 0
320
+ col_letter = col[0].column_letter
321
+ for cell in col:
322
+ if cell.value:
323
+ w = sum(2 if ord(c) > 127 else 1 for c in str(cell.value))
324
+ max_len = max(max_len, w)
325
+ ws.column_dimensions[col_letter].width = min(max_len + 4, 50)
326
+
327
+ # 最初のヘッダ行の次行でフリーズ
328
+ if first_header_row is not None:
329
+ ws.freeze_panes = ws.cell(row=first_header_row + 1, column=1)
330
 
331
  wb.save(str(output_path))
332
 
MM_tools/app/blueprints/ledger/templates/ledger/index.html CHANGED
@@ -46,7 +46,7 @@
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>
@@ -57,14 +57,14 @@
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">
@@ -75,7 +75,7 @@
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"
@@ -203,14 +203,16 @@
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>
@@ -266,7 +268,7 @@
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);
@@ -275,14 +277,37 @@
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
  // ── ステップ表示 ────────────────────────────────────────────────
 
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>帳簿・表が写った画像または PDF をアップロード(またはパスを入力)</li>
50
  <li>「Excel を生成」ボタンをクリック</li>
51
  <li>解析完了後、Excel ファイルをダウンロード</li>
52
  </ol>
 
57
  <!-- 画像アップロードエリア -->
58
  <div>
59
  <label class="block text-sm font-semibold text-gray-600 mb-2">
60
+ 画像 / PDF のアップロード
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/*,.pdf" 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">
 
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, PDF など</p>
79
  </div>
80
 
81
  <button id="change-btn"
 
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
+ <span class="text-xs bg-emerald-100 text-emerald-700 px-2 py-1 rounded-md font-mono">PDF</span>
214
  </div>
215
+ <p class="text-xs text-gray-400 mt-2">※ PDF は1ページ目のみ処理します</p>
216
  <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mt-3 mb-2">精度を上げるコツ</h3>
217
  <ul class="text-xs text-gray-500 space-y-1">
218
  <li>• 表全体が収まるように撮影</li>
 
268
  e.preventDefault();
269
  dropZone.classList.remove('drag-over');
270
  const file = e.dataTransfer.files[0];
271
+ if (file && (file.type.startsWith('image/') || file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'))) {
272
  showPreview(file);
273
  const dt = new DataTransfer();
274
  dt.items.add(file);
 
277
  });
278
 
279
  function showPreview(file) {
280
+ const isPdf = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
281
+ if (isPdf) {
282
+ preview.classList.add('hidden');
 
283
  uploadPh.classList.add('hidden');
284
  changeBtn.classList.remove('hidden');
285
+ let pdfLabel = dropZone.querySelector('#pdf-label');
286
+ if (!pdfLabel) {
287
+ pdfLabel = document.createElement('div');
288
+ pdfLabel.id = 'pdf-label';
289
+ pdfLabel.className = 'flex flex-col items-center gap-2 text-emerald-700 py-4';
290
+ dropZone.appendChild(pdfLabel);
291
+ }
292
+ pdfLabel.innerHTML = `
293
+ <svg class="w-12 h-12 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
294
+ <path stroke-linecap="round" stroke-linejoin="round"
295
+ d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
296
+ </svg>
297
+ <p class="text-sm font-semibold">${file.name}</p>
298
+ <p class="text-xs text-gray-400">${(file.size / 1024).toFixed(1)} KB(1ページ目を処理)</p>`;
299
+ } else {
300
+ const existingLabel = dropZone.querySelector('#pdf-label');
301
+ if (existingLabel) existingLabel.remove();
302
+ const reader = new FileReader();
303
+ reader.onload = (e) => {
304
+ preview.src = e.target.result;
305
+ preview.classList.remove('hidden');
306
+ uploadPh.classList.add('hidden');
307
+ changeBtn.classList.remove('hidden');
308
+ };
309
+ reader.readAsDataURL(file);
310
+ }
311
  }
312
 
313
  // ── ステップ表示 ────────────────────────────────────────────────
MM_tools/app/blueprints/ocr/__pycache__/routes.cpython-314.pyc CHANGED
Binary files a/MM_tools/app/blueprints/ocr/__pycache__/routes.cpython-314.pyc and b/MM_tools/app/blueprints/ocr/__pycache__/routes.cpython-314.pyc differ
 
MM_tools/app/blueprints/ocr/routes.py CHANGED
@@ -15,7 +15,7 @@ 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("/")
@@ -46,10 +46,11 @@ def run_ocr():
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として出力してください。"
@@ -59,17 +60,17 @@ def run_ocr():
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
  # ── モデルロード状態を通知 ──────────────────────────────────
 
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, open_image_or_pdf
19
 
20
 
21
  @ocr_bp.route("/")
 
46
 
47
  if "image" not in request.files or request.files["image"].filename == "":
48
  def _err():
49
+ yield sse_event({"error": "画像または PDF をアップロードしてください。"})
50
  return Response(stream_with_context(_err()), mimetype="text/event-stream")
51
 
52
  image_file = request.files["image"]
53
+ image_filename = image_file.filename # PDF 判定用(ジェネレータ内で使用)
54
  prompt = request.form.get("prompt", "").strip()
55
  if not prompt:
56
  prompt = "画像内のテキストをすべて読み取ってHTMLとして出力してください。"
 
60
  image_bytes = image_file.read()
61
  except Exception as exc:
62
  def _err():
63
+ yield sse_event({"error": f"ファイルの読み込みに失敗しました: {exc}"})
64
  return Response(stream_with_context(_err()), mimetype="text/event-stream")
65
 
66
  def generate():
67
  """モデルロード → OCR → SSE ストリーミングを行うジェネレータ。"""
68
+ # ── 画像を開く(PDF は1ページ目を変換)──────────────────────
69
  try:
70
+ image = open_image_or_pdf(image_bytes, image_filename)
71
  image_base64 = resize_image_to_base64(image)
72
  except Exception as exc:
73
+ yield sse_event({"error": f"ファイルの読み込みに失敗しました: {exc}"})
74
  return
75
 
76
  # ── モデルロード状態を通知 ──────────────────────────────────
MM_tools/app/blueprints/ocr/templates/ocr/index.html CHANGED
@@ -47,7 +47,7 @@
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">
@@ -58,7 +58,7 @@
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"
@@ -365,7 +365,7 @@
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);
@@ -374,14 +374,38 @@
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 共通パーサー ────────────────────────────────────────────
 
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/*,.pdf" 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">
 
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, PDF など</p>
62
  </div>
63
 
64
  <button id="change-btn"
 
365
  e.preventDefault();
366
  dropZone.classList.remove('drag-over');
367
  const file = e.dataTransfer.files[0];
368
+ if (file && (file.type.startsWith('image/') || file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'))) {
369
  showPreview(file);
370
  const dt = new DataTransfer();
371
  dt.items.add(file);
 
374
  });
375
 
376
  function showPreview(file) {
377
+ const isPdf = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
378
+ if (isPdf) {
379
+ preview.classList.add('hidden');
 
380
  placeholder.classList.add('hidden');
381
  changeBtn.classList.remove('hidden');
382
+ // PDF の場合はファイル名を表示
383
+ let pdfLabel = dropZone.querySelector('#pdf-label');
384
+ if (!pdfLabel) {
385
+ pdfLabel = document.createElement('div');
386
+ pdfLabel.id = 'pdf-label';
387
+ pdfLabel.className = 'flex flex-col items-center gap-2 text-indigo-700 py-4';
388
+ dropZone.appendChild(pdfLabel);
389
+ }
390
+ pdfLabel.innerHTML = `
391
+ <svg class="w-12 h-12 text-indigo-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
392
+ <path stroke-linecap="round" stroke-linejoin="round"
393
+ d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
394
+ </svg>
395
+ <p class="text-sm font-semibold">${file.name}</p>
396
+ <p class="text-xs text-gray-400">${(file.size / 1024).toFixed(1)} KB(1ページ目を処理)</p>`;
397
+ } else {
398
+ const existingLabel = dropZone.querySelector('#pdf-label');
399
+ if (existingLabel) existingLabel.remove();
400
+ const reader = new FileReader();
401
+ reader.onload = (e) => {
402
+ preview.src = e.target.result;
403
+ preview.classList.remove('hidden');
404
+ placeholder.classList.add('hidden');
405
+ changeBtn.classList.remove('hidden');
406
+ };
407
+ reader.readAsDataURL(file);
408
+ }
409
  }
410
 
411
  // ── SSE 共通パーサー ────────────────────────────────────────────
MM_tools/app/blueprints/vlm/__pycache__/routes.cpython-314.pyc CHANGED
Binary files a/MM_tools/app/blueprints/vlm/__pycache__/routes.cpython-314.pyc and b/MM_tools/app/blueprints/vlm/__pycache__/routes.cpython-314.pyc differ
 
MM_tools/app/blueprints/vlm/routes.py CHANGED
@@ -20,6 +20,7 @@ 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()
@@ -54,7 +55,7 @@ def process():
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:
@@ -64,18 +65,19 @@ def process():
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({
 
20
 
21
  from . import vlm_bp
22
  from app.shared.models import get_qwen_model
23
+ from app.shared.utils import open_image_or_pdf
24
 
25
  # Qwen モデルは ledger と共用するため排他ロック
26
  _model_lock = threading.Lock()
 
55
 
56
  if not image_file or not image_file.filename:
57
  def _err():
58
+ yield _sse({"error": "画像または PDF をアップロードしてください。"})
59
  return Response(stream_with_context(_err()), mimetype="text/event-stream")
60
 
61
  if not prompt:
 
65
 
66
  # SSE ジェネレータの遅延実行でリクエストストリームが閉じられる問題を防ぐため先読み
67
  image_bytes = image_file.read()
68
+ image_filename = image_file.filename # PDF 判定用
69
 
70
  def generate():
71
  from transformers import TextIteratorStreamer
72
  with _model_lock:
73
  try:
74
+ # ── 画像読み込み(PDF は1ページ目を変換)──
75
  yield _sse({
76
  "status": "processing",
77
+ "message": "ファイルを読み込み中...",
78
  "detail": "",
79
  })
80
+ image = open_image_or_pdf(image_bytes, image_filename)
81
 
82
  # ── モデルロード ──
83
  yield _sse({
MM_tools/app/blueprints/vlm/templates/vlm/index.html CHANGED
@@ -67,7 +67,7 @@
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">
@@ -75,7 +75,7 @@
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="プレビュー"
@@ -161,15 +161,40 @@
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', () => {
@@ -185,7 +210,7 @@
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;
@@ -230,7 +255,7 @@
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();
 
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/*,.pdf" 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">
 
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 / PDF など</p>
79
  </div>
80
  <!-- 画像プレビュー -->
81
  <img id="preview-img" src="" alt="プレビュー"
 
161
  const fileInfo = document.getElementById('file-info');
162
 
163
  function showPreview(file) {
164
+ const isPdf = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
165
+ if (isPdf) {
166
+ previewImg.classList.add('hidden');
 
167
  uploadPlaceholder.classList.add('hidden');
168
+ // PDF アイコン表示
169
+ let pdfLabel = dropZone.querySelector('#pdf-label');
170
+ if (!pdfLabel) {
171
+ pdfLabel = document.createElement('div');
172
+ pdfLabel.id = 'pdf-label';
173
+ pdfLabel.className = 'flex flex-col items-center gap-2 text-amber-600 pointer-events-none';
174
+ dropZone.appendChild(pdfLabel);
175
+ }
176
+ pdfLabel.innerHTML = `
177
+ <svg class="w-12 h-12 opacity-80" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
178
+ <path stroke-linecap="round" stroke-linejoin="round"
179
+ d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
180
+ </svg>
181
+ <p class="text-sm font-semibold">${file.name}</p>
182
+ <p class="text-xs text-gray-400">1ページ目を処理します</p>`;
183
  fileInfo.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
184
  fileInfo.classList.remove('hidden');
185
+ } else {
186
+ const existingLabel = dropZone.querySelector('#pdf-label');
187
+ if (existingLabel) existingLabel.remove();
188
+ const reader = new FileReader();
189
+ reader.onload = e => {
190
+ previewImg.src = e.target.result;
191
+ previewImg.classList.remove('hidden');
192
+ uploadPlaceholder.classList.add('hidden');
193
+ fileInfo.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
194
+ fileInfo.classList.remove('hidden');
195
+ };
196
+ reader.readAsDataURL(file);
197
+ }
198
  }
199
 
200
  fileInput.addEventListener('change', () => {
 
210
  e.preventDefault();
211
  dropZone.classList.remove('drag-over');
212
  const file = e.dataTransfer.files[0];
213
+ if (file && (file.type.startsWith('image/') || file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'))) {
214
  const dt = new DataTransfer();
215
  dt.items.add(file);
216
  fileInput.files = dt.files;
 
255
 
256
  runBtn.addEventListener('click', async () => {
257
  if (!fileInput.files[0]) {
258
+ alert('画像または PDF をアップロードしてください。');
259
  return;
260
  }
261
  const prompt = document.getElementById('prompt-input').value.trim();
MM_tools/app/shared/__pycache__/utils.cpython-314.pyc CHANGED
Binary files a/MM_tools/app/shared/__pycache__/utils.cpython-314.pyc and b/MM_tools/app/shared/__pycache__/utils.cpython-314.pyc differ
 
MM_tools/app/shared/utils.py CHANGED
@@ -20,6 +20,66 @@ def sse_event(data: dict) -> str:
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 文字列を返す。
 
20
  return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
21
 
22
 
23
+ def open_image_or_pdf(file_bytes: bytes, filename: str = "") -> Image.Image:
24
+ """
25
+ 画像バイト列または PDF バイト列から PIL Image (RGB) を返す。
26
+ PDF の場合は1ページ目を 2x 解像度でレンダリングして返す。
27
+
28
+ Args:
29
+ file_bytes: 画像または PDF のバイト列
30
+ filename: 元ファイル名(拡張子で PDF を判別する際に使用)
31
+
32
+ Returns:
33
+ PIL.Image: RGB 形式の画像
34
+
35
+ Raises:
36
+ ImportError: PDF 処理に pymupdf が必要なのにインストールされていない場合
37
+ ValueError: PDF にページが存在しない場合
38
+ """
39
+ is_pdf = (
40
+ filename.lower().endswith(".pdf")
41
+ or file_bytes[:4] == b"%PDF"
42
+ )
43
+ if is_pdf:
44
+ return _pdf_first_page_to_image(file_bytes)
45
+ return Image.open(io.BytesIO(file_bytes)).convert("RGB")
46
+
47
+
48
+ def _pdf_first_page_to_image(pdf_bytes: bytes) -> Image.Image:
49
+ """
50
+ PDF バイト列の1ページ目を PIL Image に変換する(内部用)。
51
+
52
+ Args:
53
+ pdf_bytes: PDF ファイルのバイト列
54
+
55
+ Returns:
56
+ PIL.Image: 1ページ目を 2x 解像度でレンダリングした RGB 画像
57
+
58
+ Raises:
59
+ ImportError: pymupdf がインストールされていない場合
60
+ ValueError: PDF にページが存在しない場合
61
+ """
62
+ try:
63
+ import fitz # pymupdf
64
+ except ImportError as exc:
65
+ raise ImportError(
66
+ "PDF の処理には pymupdf が必要です: pip install pymupdf"
67
+ ) from exc
68
+
69
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
70
+ if doc.page_count == 0:
71
+ doc.close()
72
+ raise ValueError("PDF にページが存在しません。")
73
+
74
+ page = doc[0]
75
+ mat = fitz.Matrix(2.0, 2.0) # 2x 解像度でレンダリング
76
+ pix = page.get_pixmap(matrix=mat)
77
+ img_bytes = pix.tobytes("png")
78
+ doc.close()
79
+
80
+ return Image.open(io.BytesIO(img_bytes)).convert("RGB")
81
+
82
+
83
  def resize_image_to_base64(image: Image.Image, max_size: int = 512) -> str:
84
  """
85
  PIL 画像をリサイズして Base64 エンコード済み JPEG 文字列を返す。
MM_tools/app/static/exports/whisper_text_time.txt CHANGED
@@ -1 +1 @@
1
- [1s → 26s] サーチングカット切削油は、非作成の悪いステンレス、シタン、コバール、インコネル、銅といった難作材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございます。
 
1
+ [1s → 26s] 搜索切削油是不制造好的不良钢材、锯齿、铸铁、铬、铜等难加工材料的润滑油,作为精密加工的汽车零部件、医疗设备、卫生相关零部件、航空机零部件及弱电部件的金属加工油,拥有丰富的经验。 (原文: サーチングカット切削油は、非作成の悪いステンレス、シタン、コバール、インコネル、銅といった難作材加工油としてユーザー様にご指示をいただき、精度を重視する自動車部品、医療機器部品、衛生関連部品、航空機部品、弱電部品などの金属加工油として実績がございます。