1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

とりあえず、作りつつ考えてみるの性格のため

今回は、調査資料データベースを検討するにあたっての試作をしました。

試作ので使った環境は以下の通りです:

  • OS : MAC Mini
  • Dropbox API
  • Google Gemni API
  • Google Collaboratory
  • Google Gemni

やりたいこと

Dropboxにフォルダー分けはして放り込んでいるファイルの整理

フォルダー内にあるPDFのリストを作成をしたい。←今回はここ!

(最終的にはデーターベス化をNotionで)

考えた方式

Google CollaboratoryでPythonを動かし、指定のフォルダー内にあるPDFを5ページほどスキャン。

そこから、規格番号、タイトル、Edition、発行年、DropboxのURLなどをテキストで排出する仕組み。

必要な準備

1. Dropbox APIを取得

1.1 Dropbox API Consoleにて
1.2 Create App を押し、「Scoped access」「Full Dropbox」を選択して名前を付けて作成。
1.3 Permissions タブで files.metadata.read と files.content.read にチェックを入れて保存(Submit)。
1.4 Settings タブにある「Generated access token」の Generate ボタンを押してトークンを取得します。

2. Goole Gemni APIを取得(無料枠可能)

2.1 Google AI Studio にアクセスします。

2.2 「Create API key」をクリックして、APIキーをコピーしておいてください。

3. Google CollaboratoryにPython環境をインストール

3.1 Google Colab にアクセスし、「ノートブックを新規作成」をクリックします。

3.2 最初のセル(入力欄)に、以下のライブラリインストール用コマンドを貼り付けて実行します。

以下のコードはPythonで必要な外部ライブラリをまとめてインストール・更新するコマンドです。

  • Pythonの公式パッケージ管理ツール
  • Google の Generative AI(Gemini 系)API 用公式SDK
  • Dropbox API の公式Python SDK
  • PDFファイルを読み取るためのPythonライブラリ
!pip install -q -U google-generativeai dropbox pypdf

4.Dropboxフォルダー内のPDFファイルを5ページスキャンして、以下を取得。

  • 規格番号
  • タイトル
  • バージョン
  • 発行年
import dropbox
import io
import google.generativeai as genai
from pypdf import PdfReader
import json

# --- 🛠️ 設定 ---
DROPBOX_TOKEN = 'あなたのDropboxトークン'
GEMINI_KEY = 'あなたのGemini APIキー'
TARGET_FOLDER = '/フォルダー名'

# AIの設定
genai.configure(api_key=GEMINI_KEY)
# リストに存在した最新の 2.0-flash を指定します
model = genai.GenerativeModel('models/gemini-2.0-flash')

def analyze_standards():
    dbx = dropbox.Dropbox(DROPBOX_TOKEN)
    
    try:
        res = dbx.files_list_folder(TARGET_FOLDER)
        pdf_files = [e for e in res.entries if e.name.lower().endswith('.pdf')]
        
        for entry in pdf_files:
            print(f"\n--- 解析中: {entry.name} ---")
            
            _, response = dbx.files_download(entry.path_lower)
            reader = PdfReader(io.BytesIO(response.content))
            
            full_text = ""
            for i in range(min(5, len(reader.pages))):
                text = reader.pages[i].extract_text()
                if text:
                    full_text += text + "\n"
            
            prompt = f"""
            以下のテキストは規格書の冒頭部分です。情報を抽出し、JSON形式で回答してください。
            {{
                "規格番号": "例 1171",
                "タイトル": "例 External Ignition Protection",
                "Edition": "例 2016-09",
                "発行年月": "例 2016-09"
            }}
            テキスト:
            {full_text}
            """
            
            # 実行
            result = model.generate_content(prompt)
            # Markdownの装飾を除去して表示
            print(result.text.replace('```json', '').replace('```', '').strip())

    except Exception as e:
        print(f"エラーが発生しました: {e}")

analyze_standards()

学んだこと

Google Gemniと一緒にコーディングをしました。

Google AI Studioで利用できるモデルに制限がありエラーが続きました。

以下のコードで、利用可能なモデルを表示でき、models/gemini-2.0-flashを利用しました。

エラーが出ても、根気よく何が問題か探すのが重要ですね。

Google AI Studioで利用でいるモデル一覧が以下で出せます。

import google.generativeai as genai

# 設定
GEMINI_KEY = 'あなたのAPIキー'
genai.configure(api_key=GEMINI_KEY)

# 利用可能なモデルをリストアップして表示(ここでエラーが出るか確認)
print("--- 利用可能なモデル一覧 ---")
try:
    for m in genai.list_models():
        if 'generateContent' in m.supported_generation_methods:
            print(m.name)
except Exception as e:
    print(f"モデル一覧の取得に失敗しました: {e}")

# 404が出にくい「フルパス」での指定
# 'models/' を頭に付けるのがポイントです
model = genai.GenerativeModel('models/gemini-1.5-flash')

# テスト実行
try:
    response = model.generate_content("こんにちは、テストです。")
    print("\n--- AIからの返答 ---")
    print(response.text)
except Exception as e:
    print(f"\nテスト送信エラー: {e}")
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?