GoogleのNotebookLMから抽出したデータをPythonで効率的に処理する方法を詳しく解説。API連携から自動化スクリプトの作成、実際のデータ処理パイプラインまで、実用的なコード例とともに紹介します。AI活用の業務効率化を実現したい方必見の内容です。
NotebookLMとPython連携の基礎知識
GoogleのNotebookLMは、文書やデータを分析・要約するAIツールとして多くの企業や研究者に活用されています。しかし、NotebookLMから得られた洞察やデータを、さらなる処理や分析に活用するためには、Pythonとの連携が不可欠です。
NotebookLMから抽出されるデータには、テキストの要約、キーワード抽出、関連性の分析結果などが含まれます。これらのデータを手動で処理するのは非効率的であり、特に大量のドキュメントを扱う場合には自動化が必要となります。
Python連携により実現できる主な機能として、以下が挙げられます:
・NotebookLMの出力データの自動収集
・データの構造化と整理
・複数文書間での比較分析
・可視化とレポート生成
・外部システムとの連携

環境構築とライブラリの準備
NotebookLMとPythonを連携させるための環境構築から始めましょう。必要なライブラリのインストールと基本的な設定を行います。
まず、必要なPythonライブラリをインストールします。データ処理には pandas、API通信には requests、テキスト処理には nltk や spacy を使用します。
pip install pandas requests nltk spacy beautifulsoup4 matplotlib seaborn
次に、Google Cloud APIの設定を行います。NotebookLMのデータにアクセスするためには、適切な認証情報の設定が必要です。
import os import json import pandas as pd import requests from datetime import datetime from google.auth.transport.requests import Request from google.oauth2.service_account import Credentials
認証情報の設定では、サービスアカウントキーファイルを使用します:
def setup_credentials(key_file_path): credentials = Credentials.from_service_account_file( key_file_path, scopes=['https://www.googleapis.com/auth/cloud-platform'] ) return credentials
NotebookLMからのデータ抽出方法
NotebookLMからデータを抽出する際は、複数のアプローチが可能です。最も効率的な方法は、API経由でのデータ取得です。
基本的なデータ抽出クラスを作成します:
class NotebookLMExtractor:
def __init__(self, credentials):
self.credentials = credentials
self.base_url = "https://notebooklm.googleapis.com/v1"
def get_notebook_data(self, notebook_id):
headers = {
'Authorization': f'Bearer {self.credentials.token}',
'Content-Type': 'application/json'
}
url = f"{self.base_url}/notebooks/{notebook_id}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"データ取得エラー: {response.status_code}")
特定のノートブックから要約データを抽出する関数:
def extract_summaries(self, notebook_id):
data = self.get_notebook_data(notebook_id)
summaries = []
for item in data.get('items', []):
if item.get('type') == 'summary':
summaries.append({
'id': item.get('id'),
'title': item.get('title'),
'content': item.get('content'),
'created_at': item.get('created_at'),
'keywords': item.get('keywords', [])
})
return summaries

データ処理パイプラインの構築
抽出したデータを効率的に処理するためのパイプラインを構築します。このパイプラインでは、データの前処理、構造化、分析までを自動化します。
データ処理パイプラインのメインクラス:
class DataProcessor:
def __init__(self):
self.raw_data = []
self.processed_data = pd.DataFrame()
def load_data(self, extractor, notebook_ids):
for notebook_id in notebook_ids:
try:
summaries = extractor.extract_summaries(notebook_id)
self.raw_data.extend(summaries)
print(f"ノートブック {notebook_id} から {len(summaries)} 件のデータを取得")
except Exception as e:
print(f"エラー: {notebook_id} - {str(e)}")
def preprocess_data(self):
df = pd.DataFrame(self.raw_data)
# 日付データの変換
df['created_at'] = pd.to_datetime(df['created_at'])
# テキストの前処理
df['content_length'] = df['content'].str.len()
df['keyword_count'] = df['keywords'].apply(len)
# 重複データの削除
df = df.drop_duplicates(subset=['content'])
self.processed_data = df
return df
テキストデータの詳細分析機能:
def analyze_text_content(self):
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
nltk.download('vader_lexicon')
analyzer = SentimentIntensityAnalyzer()
sentiments = []
for content in self.processed_data['content']:
scores = analyzer.polarity_scores(content)
sentiments.append(scores['compound'])
self.processed_data['sentiment_score'] = sentiments
return self.processed_data
自動化スクリプトの実装
定期的なデータ抽出と処理を自動化するスクリプトを実装します。このスクリプトにより、手動作業を大幅に削減できます。
自動化スクリプトのメインロジック:
class AutomationManager:
def __init__(self, config_path):
with open(config_path, 'r') as f:
self.config = json.load(f)
self.extractor = NotebookLMExtractor(
setup_credentials(self.config['credentials_path'])
)
self.processor = DataProcessor()
def run_daily_extraction(self):
print(f"日次データ抽出開始: {datetime.now()}")
# データ抽出
notebook_ids = self.config['notebook_ids']
self.processor.load_data(self.extractor, notebook_ids)
# データ処理
df = self.processor.preprocess_data()
df = self.processor.analyze_text_content()
# 結果の保存
output_path = f"processed_data_{datetime.now().strftime('%Y%m%d')}.csv"
df.to_csv(output_path, index=False, encoding='utf-8-sig')
print(f"処理完了: {len(df)} 件のデータを処理")
return df
スケジュール実行機能:
def setup_scheduler(self):
import schedule
import time
schedule.every().day.at("09:00").do(self.run_daily_extraction)
schedule.every().hour.do(self.run_incremental_update)
while True:
schedule.run_pending()
time.sleep(60)
def run_incremental_update(self):
# 増分更新ロジック
cutoff_time = datetime.now() - timedelta(hours=1)
# 最新データのみを処理
pass

データ可視化とレポート生成
処理されたデータを効果的に可視化し、レポートを自動生成する機能を実装します。
可視化クラスの実装:
import matplotlib.pyplot as plt
import seaborn as sns
class DataVisualizer:
def __init__(self, data):
self.data = data
plt.style.use('seaborn-v0_8')
def create_summary_dashboard(self):
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# データ量の時系列推移
daily_counts = self.data.groupby(
self.data['created_at'].dt.date
).size()
axes[0, 0].plot(daily_counts.index, daily_counts.values)
axes[0, 0].set_title('日別データ取得数')
axes[0, 0].tick_params(axis='x', rotation=45)
# 感情分析結果の分布
axes[0, 1].hist(self.data['sentiment_score'], bins=30, alpha=0.7)
axes[0, 1].set_title('感情スコア分布')
# コンテンツ長の分布
axes[1, 0].boxplot(self.data['content_length'])
axes[1, 0].set_title('コンテンツ長の分布')
# キーワード数の分布
axes[1, 1].scatter(
self.data['content_length'],
self.data['keyword_count'],
alpha=0.6
)
axes[1, 1].set_title('コンテンツ長 vs キーワード数')
plt.tight_layout()
return fig
レポート生成機能:
def generate_report(self, output_path):
from datetime import datetime
report_data = {
'generated_at': datetime.now(),
'total_records': len(self.data),
'date_range': {
'start': self.data['created_at'].min(),
'end': self.data['created_at'].max()
},
'summary_stats': {
'avg_content_length': self.data['content_length'].mean(),
'avg_keyword_count': self.data['keyword_count'].mean(),
'avg_sentiment': self.data['sentiment_score'].mean()
}
}
# HTMLレポートの生成
html_template = """
NotebookLM データ分析レポート
NotebookLM データ分析レポート
生成日時: {generated_at}
データサマリー
- 総レコード数: {total_records}
- 平均コンテンツ長: {avg_content_length:.1f}
- 平均キーワード数: {avg_keyword_count:.1f}
- 平均感情スコア: {avg_sentiment:.3f}

エラーハンドリングとログ管理
本格的な運用では、適切なエラーハンドリングとログ管理が重要です。
ログ管理システムの実装:
import logging
from logging.handlers import RotatingFileHandler
class LogManager:
def __init__(self, log_file='notebooklm_processor.log'):
self.logger = logging.getLogger('NotebookLMProcessor')
self.logger.setLevel(logging.INFO)
handler = RotatingFileHandler(
log_file, maxBytes=10*1024*1024, backupCount=5
)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def log_info(self, message):
self.logger.info(message)
def log_error(self, message, exception=None):
if exception:
self.logger.error(f"{message}: {str(exception)}")
else:
self.logger.error(message)
実践的な活用事例
NotebookLMとPythonの連携により、以下のような実践的な活用が可能になります:
1. 研究論文の自動分析
複数の研究論文をNotebookLMで分析し、Pythonで傾向分析や引用関係の可視化を行う。
2. 企業文書の定期レビュー
社内文書の変更点を自動検出し、重要な更新をアラートとして通知する。
3. 競合分析の自動化
競合他社の公開情報を定期的に分析し、トレンドの変化を追跡する。
これらの活用により、情報処理の効率化と洞察の質的向上を同時に実現できます。
まとめ
NotebookLMとPythonの連携により、AIによる文書分析の可能性は大きく広がります。適切な自動化パイプラインの構築により、手動作業の削減と分析精度の向上を実現できます。
今回紹介した手法を参考に、自組織のニーズに合わせたカスタマイズを行い、AI活用の業務効率化を推進してください。継続的な改善と運用監視により、さらなる価値創出が期待できます。








