Python 関係の基本用語解説
FastAPI
FastAPI は現代的な高性能な Python ウェブフレームワークで、高速にWeb APIをつくることができます!
pip
pip は Python のパッケージ管理ツールです。Python で書かれたソフトウェアパッケージ(ライブラリ)をインストール・管理するためのコマンドラインツールです。
Node.jsの世界に慣れていれば、requirements.txt は package.json の dependencies セクションだけを取り出したようなもの、と考えるとわかりやすいでしょう。
uvicornとは?
FastAPIアプリ単体ではHTTPリクエストを受け取れない、、そこで非同期通信を可能にするPython用の超高速な「ASGIサーバー」
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
構成ファイル
大枠のフローとして「フロントエンドから直接FastAPIへアクセスするのではなく、Expressサーバーを経由して、API連携します」
Expressフレームワークを使用
Expressでフロントエンド処理とFastAPI中継(ローカルにNode.jsインストール済み)
1. クライアント側 (index.html)
│
├── 画像ファイル選択
│ └── <input type="file">で画像を選択
│
├── フォーム送信
│ └── FormDataオブジェクトを作成
│
└── APIリクエスト送信
└── fetch('http://localhost:3000/fastapi')
2. Express サーバー (server.js - Port:3000)
│
├── 静的ファイル配信
│ └── index.htmlの提供
│
├── ファイル受信
│ └── multerによるファイル処理
│
└── FastAPIへ転送
└── fetch('http://localhost:8000/ocr')
3. FastAPI サーバー (main.py - Port:8000)
│
├── CORS処理
│ └── クロスオリジンリクエストの許可
│
├── OCR処理
│ └── 画像からテキスト抽出
│
└── レスポンス返却
└── JSON形式で結果を返却
4. データの戻り
│
├── FastAPI → Express
│ └── OCR結果のJSON
│
├── Express → クライアント
│ └── JSONデータの転送
│
└── クライアント表示
└── 結果をHTML上に表示
Express/
├── server.js # Express サーバー(ポート3000)
├── index.html # フロントエンドのメインページ
├── main.py # FastAPI サーバー(ポート8000)
├── package.json # npm パッケージ設定
├── package-lock.json # npm パッケージのバージョン固定
└── node_modules/ # npm パッケージのインストール先
├── express/
├── cors/
├── multer/
├── node-fetch/
├── form-data/
└── ...
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FastAPIにPOSTリクエスト</title>
<style>
.result-area {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
min-height: 100px;
}
</style>
</head>
<body>
<h1>画像からテキストを抽出</h1>
<form id="ocr-form">
<div>
<label for="image-file">画像ファイル:</label>
<!-- accept="imgage/*"とは -->
<input type="file" id="image-file" accept="image/*" required>
</div>
<div style="margin-top: 10px;">
<button type="submit">テキスト抽出</button>
</div>
</form>
<div class="result-area" id="result">
<p>抽出結果がここに表示されます...</p>
</div>
<script>
// 送信ボタンクリック時の処理
document.getElementById('ocr-form').addEventListener('submit', async function(e) {
e.preventDefault(); // デフォルトの動作を防止
const fileInput = document.getElementById('image-file');
const resultDiv = document.getElementById('result');
if (!fileInput.files.length) {
resultDiv.innerHTML = '<p>ファイルを選択してください</p>';
return;
}
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
resultDiv.innerHTML = '<p>処理中...</p>';
try {
const response = await fetch('http://localhost:3000/fastapi', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('APIリクエストに失敗しました');
}
const data = await response.json();
resultDiv.innerHTML = `<p>抽出されたテキスト:</p><pre>${data.extracted_text}</pre>`;
} catch (error) {
resultDiv.innerHTML = `<p>エラー: ${error.message}</p>`;
console.error('Error:', error);
}
});
</script>
</body>
</html>
server.js
import express from 'express';
import multer from 'multer';
import fetch from 'node-fetch';
const app = express();
// 静的ファイルの配信設定
app.use(express.static('.'));
// アップロードされたファイルをメモリに保存
const upload = multer({ storage: multer.memoryStorage() });
// FastAPIエンドポイント
app.post('/fastapi', upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'ファイルがアップロードされていません' });
}
// Blobを使用してFormDataを作成
const formData = new FormData();
const blob = new Blob([req.file.buffer], { type: req.file.mimetype });
formData.append('file', blob, req.file.originalname);
const response = await fetch('http://localhost:8000/express-fastapi', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('FastAPIサーバーでエラーが発生しました');
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('エラー:', error);
res.status(500).json({ error: 'リクエスト処理中にエラーが発生しました' });
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`サーバーが起動しました: http://localhost:${PORT}`);
});
FastApi
テストで確認用にシンプルな構成
python未インストールでDocker開発しました
プロジェクトルート/
├── app/
│ ├── __pycache__/ # Pythonのコンパイル済みファイル(自動生成)
│ │ └── *.pyc
│ └── main.py # FastAPIのメインアプリケーションファイル
│
├── .dockerignore # Dockerビルド時に除外するファイルの設定
├── Dockerfile # Dockerイメージのビルド設定
└── requirements.txt # Pythonパッケージの依存関係リスト
Dockerfile
# Pythonの公式イメージをベースとして使用
FROM python:3.9-slim
# Tesseract OCRとその日本語サポートのインストール
RUN apt-get update && apt-get install -y \
tesseract-ocr \
tesseract-ocr-jpn \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# コンテナ内の作業ディレクトリを/appに設定
WORKDIR /app
# 依存関係ファイルをコピー
COPY requirements.txt .
# 依存関係をインストール
RUN pip install --no-cache-dir -r requirements.txt
# 開発時はボリュームマウントを使用するため、COPYは不要
# COPY app/ .
# 開発用のコマンド
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
requirements.txt
# requirements.txt
# FastAPI: Webフレームワーク
fastapi==0.104.1
# Uvicorn: ASGIサーバー(FastAPIを実行するために必要)
uvicorn==0.23.2
# multipart: ファイルアップロード処理に必要
python-multipart==0.0.6
# pytesseract: TesseractのPythonラッパー(OCR処理用)
pytesseract==0.3.10
# Pillow: 画像処理ライブラリ
Pillow==10.0.1
main.py
from fastapi import FastAPI, File, UploadFile # FastAPIとファイルアップロード関連のインポート
from fastapi.middleware.cors import CORSMiddleware # CORSを許可するためのミドルウェア
import pytesseract # OCRライブラリ
from PIL import Image # 画像処理ライブラリ
import io # バイナリデータ処理用
import logging
# ロギングの設定
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# FastAPIアプリケーションのインスタンス作成
app = FastAPI(title="Simple OCR API")
# CORSを許可するためのミドルウェアを追加
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 開発環境では一時的にすべてのオリジンを許可
allow_credentials=False, # '*'を使用する場合はFalseにする必要がある
allow_methods=["*"],
allow_headers=["*"],
)
# ルートエンドポイント(/)へのGETリクエスト処理
@app.get("/")
def read_root():
return {"message": "Welcome to Simple OCR API"} # JSONレスポンスを返す
# fastapiエンドポイント(/express-fastapi)へのPOSTリクエスト処理
@app.post("/express-fastapi")
async def extract_text(file: UploadFile = File(...)):
try:
# アップロードされた画像ファイルを読み込む
image_bytes = await file.read()
logger.debug(f"Received file size: {len(image_bytes)} bytes")
logger.debug(f"File content type: {file.content_type}")
# 画像オブジェクトを作成
image = Image.open(io.BytesIO(image_bytes))
logger.debug(f"Image size: {image.size}")
logger.debug(f"Image mode: {image.mode}")
# Tesseract OCRでテキスト抽出を実行
logger.debug("Starting OCR processing...")
text = pytesseract.image_to_string(image, lang='jpn+eng')
logger.debug(f"OCR completed. Extracted text: {text}")
return {"extracted_text": text.strip()}
except Exception as e:
logger.error(f"Error occurred: {str(e)}", exc_info=True)
return {"error": str(e)}
pytesseract
pytesseractはPythonからTesseract OCR(光学文字認識エンジン)を利用するためのラッパーライブラリです。画像からテキストを抽出するのに使用されます。
pytesseractの具体的な使用方法
text = pytesseract.image_to_string(image, lang='jpn+eng')
FastAPIの開発を依頼
「ExpressサーバーからPOSTリクエストでOCR処理用の画像を送信するためのFastAPIサービスを開発していただきたいです。」
「画像はFormData形式で送信され、これをFastAPI側で受け取っていただき、画像内のテキストを抽出をお願いします」
「抽出したテキストは {“extracted_text”: “抽出されたテキスト”} という形式のJSONで返却してください。エラー発生時は {“error”: “エラーメッセージ”} 形式でレスポンスを返してください。」
「使用するエンドポイントは /express-fastapi としてください。」
「日本語と英語の両方のテキストを認識できるよう設定し、ExpressサーバーからのクロスオリジンリクエストのためにCORS設定も必要です。デバッグがしやすいよう、ログレベルはDEBUGで設定してください。」
複数ユーザーが同時にリクエストする場合の区別方法
上記実装の場合は複数人ユーザーの同時アクセスを考慮で来てません、、
cookieParser(ミドルウェアモジュール)
Node.jsとExpressで使用されるミドルウェアです。
cookieParserを使用することで、「クライアントから送信されたHTTPリクエストのCookie」をサーバーでオブジェクト管理できます
- インストール: npm install cookie-parser
- ミドルウェアとして登録
const cookieParser = require('cookie-parser');
const { v4: uuidv4 } = require('uuid'); // UUIDを生成するためのライブラリ
app.use(cookieParser());
// ユーザーIDのCookieがなければ作成する処理
app.use((req, res, next) => {
if (!req.cookies.userId) {
const newUserId = uuidv4(); // ← ここでユーザーIDを生成
res.cookie('userId', newUserId, { httpOnly: true });
console.log('新しいuserIdを発行:', newUserId);
}
next();
});
✅ 確認方法(Google Chromeの場合)
- 対象のページを開いた状態で
F12
キー もしくは 右クリック →「検証」- 上部のタブから【アプリケーション】を選択
- 左側のメニューで【ストレージ】→【Cookie】→
http://localhost
~ をクリック - 右側にCookieの一覧が表示されます
🍪 表に表示される内容
列名 | 内容 |
---|---|
Name | Cookieのキー名(例: userId ) |
Value | 値(例: aef1c23d-xxxx-xxxx-xxxx-123456abcdef ) |
Domain | localhost など |
Path | / など |
Expires / Max-Age | 有効期限(設定していれば) |
HttpOnly | JSから見えない場合は✔が付く |
Secure | HTTPSのみなら✔が付く |
SameSite | Cookieの送信制御(Lax , Strict , None など) |
ユーザー識別のロジック
ユーザーID追跡:
- ブラウザ → Express: CookieでユーザーID
abc123
を送信 - Express側:
req.cookies.userId
からユーザーIDを取得
APIリクエスト:
- Express → Python: リクエストJSONに
"userId": "abc123"
を含める - Python側: このIDで処理を紐付け
レスポンス返却:
- Python → Express: レスポンスJSONに同じ
"userId": "abc123"
を含めて返す - Express側: レスポンスのユーザーIDが元のリクエストと一致するか検証
クライアントへの返却:
- Express → ブラウザ: 処理結果を返す
app.post('/api/endpoint', upload.single('file'), async (req, res) => {
try {
// 1. リクエスト元のユーザーIDを取得
const userId = req.cookies.userId;
// 2. Python APIにリクエスト送信(ユーザーIDを含める)
const apiResponse = await fetch('http://python/process', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: userId,
// その他のデータ
})
});
const result = await apiResponse.json();
// 3. レスポンスのユーザーIDが一致するか検証
if (result.userId !== userId) {
console.error('ユーザーID不一致:', { expected: userId, received: result.userId });
return res.status(500).json({ error: 'ユーザー識別エラー' });
}
// 4. 正しいユーザーへレスポンスを返す
return res.json({
success: true,
text: result.text,
// その他の結果データ
});
} catch (error) {
res.status(500).json({ error: '処理に失敗しました' });
}
});
そもそもクッキーに保存するまでもない
import express from 'express';
import multer from 'multer';
import fetch from 'node-fetch';
import { v4 as uuidv4 } from 'uuid';
const app = express();
const upload = multer({ storage: multer.memoryStorage() });
app.post('/fastapi', upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'ファイルがありません' });
}
// Cookieではなくここで都度 userId を生成
const userId = uuidv4();
const formData = new FormData();
const blob = new Blob([req.file.buffer], { type: req.file.mimetype });
formData.append('file', blob, req.file.originalname);
formData.append('userId', userId); // ← ここで送るだけ
const response = await fetch('http://localhost:8000/express-fastapi', {
method: 'POST',
body: formData,
});
const data = await response.json();
// 必要なら userId を含めてクライアントに返す
res.json({
userId: data.userId,
extracted_text: data.extracted_text,
});
} catch (err) {
res.status(500).json({ error: '処理に失敗しました' });
}
});
Pythonで使える便利ライブラリまとめ(boto3 / moviepy / pydub / Poetry)
✅ boto3:AWSをPythonで操作できるライブラリ
一言で言うと:
Amazonが提供しているクラウドサービス「AWS」を、Pythonで操作できるようにするライブラリです。
できること例:
- S3にファイルをアップロード・ダウンロード
- DynamoDBでデータを読み書き
- EC2インスタンスを起動・停止
補足ワード:
- AWS(Amazon Web Services):サーバーやストレージなどをネット経由で使えるサービス群
- ライブラリ:便利な機能の詰まったツールセット
✅ moviepy:動画をPythonで編集・合成できるライブラリ
一言で言うと:
Pythonだけで簡単な動画編集ができちゃうライブラリです。
できること例:
- 動画のカット(トリミング)
- 動画同士の結合
- テキストや画像の挿入
- GIFの作成
補足ワード:
- フレーム:動画を構成する1枚1枚の静止画のこと
✅ pydub:音声ファイルをPythonで加工・編集できるライブラリ
一言で言うと:
音声ファイル(MP3やWAVなど)を切ったりつなげたり、加工できるライブラリです。
できること例:
- 音声のトリミング(カット)
- フェードイン・アウトの追加
- 音量の調整
- ファイル形式の変換(MP3⇔WAVなど)
補足ワード:
- フェード:音が徐々に大きくなったり小さくなったりする演出
- コーデック:音声データを圧縮・解凍する技術
✅ Poetry:Pythonのプロジェクト管理ツール
一言で言うと:
Pythonのプロジェクトを、スッキリ管理できるツールです。
できること例:
- 依存ライブラリの管理(バージョンもOK)
- 仮想環境の自動作成
- ライブラリの公開も楽チン
補足ワード:
- 仮想環境:プロジェクトごとにライブラリの環境を分ける仕組み
- 依存関係:このライブラリが動くために必要な他のライブラリのこと