nullai-knowledge-system / IATH_IMPORT_GUIDE.md
kofdai's picture
Deploy NullAI Knowledge System to Spaces
075a2b6 verified

.iathファイル インポートガイド

このドキュメントでは、dendritic-memory-editorや他のソースからエクスポートした.iathファイルをNullAI project_locateプロジェクトにインポートする方法を説明します。

目次

  1. 前提条件
  2. 方法1: cURLを使ったインポート
  3. 方法2: Pythonスクリプトを使ったインポート
  4. 方法3: Web UIを使ったインポート
  5. データベース設定の変更
  6. トラブルシューティング

前提条件

1. バックエンドサーバーの起動

cd /Users/motonishikoudai/project_locate/huggingface_repo/backend
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

2. データベースの初期化(初回のみ)

cd /Users/motonishikoudai/project_locate/huggingface_repo/backend
python create_db.py

3. .iathファイルの確認

エクスポートした.iathファイルがJSON version 2形式であることを確認します:

head -20 your_file.iath | python3 -m json.tool

正しい形式の例:

{
  "version": 2,
  "header": {
    "domain_code": 1,
    "tile_count": 5,
    "created_at": "2025-12-04T00:04:37.775Z",
    "domain": "Medical"
  },
  "tiles": [...]
}

方法1: cURLを使ったインポート

ステップ1: ユーザー登録(初回のみ)

curl -X POST http://localhost:8000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "your_email@example.com",
    "password": "your_password",
    "username": "your_username"
  }'

ステップ2: ログインしてトークンを取得

curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "your_email@example.com",
    "password": "your_password"
  }'

レスポンス例:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

ステップ3: .iathファイルをインポート

# トークンを環境変数に保存
export AUTH_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

# .iathファイルをアップロード
curl -X POST http://localhost:8000/api/knowledge/import/iath \
  -H "Authorization: Bearer $AUTH_TOKEN" \
  -F "file=@/path/to/your/Medical_tiles_1764806677601.iath"

成功レスポンス例:

{
  "success": true,
  "domain": "Medical",
  "total_tiles": 5,
  "imported": 3,
  "updated": 2,
  "errors": 0,
  "message": "Successfully processed 5 tiles from Medical"
}

方法2: Pythonスクリプトを使ったインポート

インポートスクリプトの作成

import_iath.pyというファイルを作成します:

#!/usr/bin/env python3
"""
.iath ファイルを NullAI データベースにインポートするスクリプト
"""
import requests
import sys
import os
from pathlib import Path

# 設定
API_BASE_URL = "http://localhost:8000"
EMAIL = "your_email@example.com"
PASSWORD = "your_password"

def login(email: str, password: str) -> str:
    """ログインしてアクセストークンを取得"""
    response = requests.post(
        f"{API_BASE_URL}/api/auth/login",
        json={"email": email, "password": password}
    )
    response.raise_for_status()
    return response.json()["access_token"]

def import_iath_file(file_path: str, token: str):
    """
    .iath ファイルをインポート

    Args:
        file_path: .iathファイルのパス
        token: 認証トークン
    """
    if not os.path.exists(file_path):
        print(f"❌ エラー: ファイルが見つかりません: {file_path}")
        return False

    print(f"📦 インポート中: {file_path}")

    with open(file_path, 'rb') as f:
        files = {'file': (os.path.basename(file_path), f, 'application/json')}
        headers = {'Authorization': f'Bearer {token}'}

        response = requests.post(
            f"{API_BASE_URL}/api/knowledge/import/iath",
            headers=headers,
            files=files
        )

    if response.status_code == 200:
        result = response.json()
        print(f"✅ インポート成功!")
        print(f"   ドメイン: {result['domain']}")
        print(f"   総タイル数: {result['total_tiles']}")
        print(f"   新規インポート: {result['imported']}")
        print(f"   更新: {result['updated']}")
        print(f"   エラー: {result['errors']}")

        if result.get('error_details'):
            print(f"⚠️  エラー詳細:")
            for error in result['error_details']:
                print(f"     - {error}")

        return True
    else:
        print(f"❌ インポート失敗: {response.status_code}")
        print(f"   エラー: {response.text}")
        return False

def main():
    if len(sys.argv) < 2:
        print("使い方: python import_iath.py <.iath ファイルパス> [追加ファイル...]")
        print("\n例:")
        print("  python import_iath.py Medical_tiles.iath")
        print("  python import_iath.py *.iath")
        sys.exit(1)

    # ログイン
    print("🔐 ログイン中...")
    try:
        token = login(EMAIL, PASSWORD)
        print("✅ ログイン成功")
    except Exception as e:
        print(f"❌ ログイン失敗: {e}")
        sys.exit(1)

    # 各ファイルをインポート
    file_paths = sys.argv[1:]
    success_count = 0

    for file_path in file_paths:
        if import_iath_file(file_path, token):
            success_count += 1
        print()  # 空行

    print(f"\n📊 結果: {success_count}/{len(file_paths)} ファイルのインポートに成功しました")

if __name__ == "__main__":
    main()

スクリプトの実行

# 実行権限を付与
chmod +x import_iath.py

# 単一ファイルをインポート
python import_iath.py /Users/motonishikoudai/Downloads/Medical_tiles_1764806677601.iath

# 複数ファイルを一括インポート
python import_iath.py /Users/motonishikoudai/Downloads/*.iath

方法3: Web UIを使ったインポート

ステップ1: フロントエンドの起動

cd /Users/motonishikoudai/project_locate/huggingface_repo/frontend
npm install
npm run dev

ステップ2: ブラウザでアクセス

  1. ブラウザで http://localhost:5173 を開く
  2. ログインまたは新規登録
  3. Knowledge Base画面に移動
  4. 「Import .iath File」ボタンをクリック
  5. .iathファイルを選択してアップロード
  6. インポート結果を確認

フロントエンドにインポート機能を追加する場合

frontend/src/components/IathImport.tsx を作成:

import React, { useState } from 'react';
import { useAuth } from '../contexts/AuthContext';

export function IathImportButton() {
  const [isImporting, setIsImporting] = useState(false);
  const { token } = useAuth();

  const handleImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setIsImporting(true);

    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch(
        `${import.meta.env.VITE_API_URL}/api/knowledge/import/iath`,
        {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`
          },
          body: formData
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || 'Import failed');
      }

      const result = await response.json();
      alert(`Import successful!\n\nDomain: ${result.domain}\nImported: ${result.imported}\nUpdated: ${result.updated}`);

      // ページをリロードしてデータを更新
      window.location.reload();

    } catch (error: any) {
      console.error('Error importing IATH:', error);
      alert(`Import failed: ${error.message}`);
    } finally {
      setIsImporting(false);
    }
  };

  return (
    <div className="import-button-container">
      <input
        type="file"
        id="iath-import"
        accept=".iath"
        onChange={handleImport}
        disabled={isImporting}
        style={{ display: 'none' }}
      />
      <label
        htmlFor="iath-import"
        className={`px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 cursor-pointer ${
          isImporting ? 'opacity-50 cursor-not-allowed' : ''
        }`}
      >
        {isImporting ? 'Importing...' : 'Import .iath File'}
      </label>
    </div>
  );
}

データベース設定の変更

使用するデータベースを切り替える

方法1: 環境変数で設定(推奨)

backend/.env ファイルを作成:

# SQLiteの場合(デフォルト)
DATABASE_URL=sqlite:///./sql_app.db

# 別のSQLiteファイルを使用
DATABASE_URL=sqlite:///./nullai_knowledge.db

# PostgreSQLの場合
DATABASE_URL=postgresql://username:password@localhost:5432/nullai_db

# MySQLの場合
DATABASE_URL=mysql://username:password@localhost:3306/nullai_db

方法2: PostgreSQLに切り替え

  1. PostgreSQLをインストール:
brew install postgresql
brew services start postgresql
  1. データベースを作成:
createdb nullai_db
  1. 必要なPythonパッケージをインストール:
pip install psycopg2-binary
  1. .envファイルを設定:
DATABASE_URL=postgresql://your_username@localhost:5432/nullai_db
  1. データベースを初期化:
cd backend
python create_db.py

方法3: 複数のデータベースを管理

異なる.envファイルを作成して切り替え:

# .env.development
DATABASE_URL=sqlite:///./dev_database.db

# .env.production
DATABASE_URL=postgresql://user:pass@localhost:5432/nullai_prod

# .env.testing
DATABASE_URL=sqlite:///./test_database.db

使用時に指定:

# 開発環境
cp .env.development .env
uvicorn app.main:app --reload

# 本番環境
cp .env.production .env
uvicorn app.main:app

トラブルシューティング

問題1: "Invalid .iath file format" エラー

原因: .iathファイルのJSON形式が不正

解決方法:

# ファイルの形式を確認
python3 -m json.tool your_file.iath

# version, header, tiles フィールドが存在することを確認

問題2: "Unauthorized" エラー

原因: 認証トークンが無効または期限切れ

解決方法:

# 再ログインしてトークンを取得
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "your_email", "password": "your_password"}'

問題3: データベース接続エラー

原因: DATABASE_URLが正しく設定されていない

解決方法:

# .envファイルを確認
cat backend/.env

# データベースファイルの存在を確認(SQLiteの場合)
ls -la backend/*.db

# データベースを再初期化
cd backend
python create_db.py

問題4: 一部のタイルがインポートされない

原因: タイルデータに不完全な情報が含まれている

解決方法:

  • レスポンスのerror_detailsフィールドを確認
  • 問題のあるタイルを特定して手動で修正
  • contentまたはtitleが空のタイルは自動的にスキップされます

問題5: バックエンドサーバーが起動しない

原因: ポート8000が既に使用されている、または依存関係が不足

解決方法:

# ポートの使用状況を確認
lsof -i :8000

# 依存関係を再インストール
cd backend
pip install -r requirements.txt

# 別のポートで起動
uvicorn app.main:app --reload --port 8001

エクスポート機能

インポートしたデータを.iath形式で再エクスポートすることもできます:

API経由でエクスポート

# すべてのドメインをエクスポート
curl -X GET "http://localhost:8000/api/knowledge/export/iath" \
  -H "Authorization: Bearer $AUTH_TOKEN" \
  -o exported_all.iath

# 特定のドメインをエクスポート
curl -X GET "http://localhost:8000/api/knowledge/export/iath?domain_id=medical" \
  -H "Authorization: Bearer $AUTH_TOKEN" \
  -o exported_medical.iath

まとめ

このガイドでは、以下の方法で.iathファイルをインポートする方法を説明しました:

  1. cURL: コマンドラインから直接インポート
  2. Pythonスクリプト: 一括インポートや自動化に最適
  3. Web UI: ユーザーフレンドリーなインターフェース

また、データベース設定の変更方法も説明しました。

ご質問やトラブルがあれば、GitHubのIssueまでお問い合わせください: