import os import sys import pkg_resources # 必要なライブラリをインストール required_packages = [ 'Flask', 'torch', 'transformers', 'pandas', 'scikit-learn', 'tqdm', 'matplotlib', 'numpy', 'fugashi', 'ipadic', 'sudachipy', 'sudachidict-core', 'neologdn' ] for package in required_packages: try: pkg_resources.require(package) except pkg_resources.DistributionNotFound: print(f"Installing {package}...") os.system(f'pip install {package}') from flask import Flask, render_template, request, jsonify from predictor import load_models, predict_text import sys import torch app = Flask(__name__) # アプリケーション起動時にモデルを読み込み print("=== アプリケーション起動 ===") print(f"Python version: {sys.version}") print("Library check complete.") # モデルを読み込み try: load_models() print("✅ モデルの読み込みが完了しました") except Exception as e: print(f"❌ モデルの読み込みに失敗しました: {e}") print("⚠️ モデルファイルが存在しない可能性があります") @app.route('/') def index(): return render_template('index.html') @app.route('/', methods=['POST']) def predict(): input_text = request.form.get('text', '') print("=== 推測ボタンが押されました ===", flush=True) print(f"入力されたテキスト: '{input_text}'", flush=True) print(f"テキストの長さ: {len(input_text)} 文字", flush=True) print("================================", flush=True) sys.stdout.flush() if not input_text.strip(): print("⚠️ 空のテキストが入力されました", flush=True) return render_template('index.html', error="テキストを入力してください。", input_text=input_text) try: # 予測を実行 result = predict_text(input_text) print("--- 予測結果 ---") print(f"入力文: {input_text}") print("年代の確率:") for age, percentage in result['age_percentages'].items(): print(f" {age}: {percentage}%") print("性別の確率:") for gender, percentage in result['gender_percentages'].items(): print(f" {gender}: {percentage}%") print("-----------------") return render_template('index.html', result=result, input_text=input_text) except Exception as e: print(f"予測中にエラーが発生しました: {e}", flush=True) import traceback traceback.print_exc() return render_template('index.html', error=f"予測中にエラーが発生しました: {str(e)}", input_text=input_text) if __name__ == '__main__': # Hugging Face Spaces用の設定 port = int(os.environ.get('PORT', 5000)) debug = os.environ.get('FLASK_ENV') == 'development' print(f"アプリケーションを起動します: http://0.0.0.0:{port}") app.run(host='0.0.0.0', port=port, debug=debug)