# -*- coding: utf-8 -*- """ AI 뉴스 & 허깅페이스 트렌딩 LLM 분석 웹앱 (완전판 v3.2) 파일명: app_advanced.py 주요 기능: 1. SQLite DB 영구 스토리지 2. AI Times 실시간 뉴스 크롤링 (2개 섹션) 3. 실제 Hugging Face Trending API 연동 (모델/스페이스 30위) 4. Fireworks AI (Qwen3-235B) 실시간 LLM 분석 - 뉴스 초등학생 수준 분석 - 모델 카드 자동 분석 (README.md) - 스페이스 코드 자동 분석 (app.py) 5. 탭 UI (뉴스/모델/스페이스) 실행 방법: 1. pip install Flask requests beautifulsoup4 huggingface_hub 2. export FIREWORKS_API_KEY="your-api-key-here" # 선택사항 (없으면 템플릿 모드) 3. python app_advanced.py 4. 브라우저에서 http://localhost:7860 접속 환경변수: - FIREWORKS_API_KEY: Fireworks AI API 키 (선택, 더 나은 분석) - PORT: 서버 포트 (기본값: 7860) """ from flask import Flask, render_template_string, jsonify, request import requests import json from datetime import datetime from typing import List, Dict, Optional import os import sys import sqlite3 import time from huggingface_hub import HfApi from bs4 import BeautifulSoup import re # Flask 앱 초기화 app = Flask(__name__) app.config['JSON_AS_ASCII'] = False # 데이터베이스 파일 경로 DB_PATH = 'ai_news_analysis.db' # ============================================ # HTML 템플릿 (탭 UI 포함) # ============================================ HTML_TEMPLATE = """
초등학생도 이해하는 AI 트렌드 분석 시스템 🎓
{str(e)}
{error_detail}
""", 500
@app.route('/api/data')
def api_data():
"""JSON API"""
try:
force_refresh = request.args.get('refresh', 'false').lower() == 'true'
analyzer = AdvancedAIAnalyzer()
data = analyzer.get_all_data(force_refresh=force_refresh)
return jsonify({
'success': True,
'data': data
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/refresh')
def api_refresh():
"""강제 새로고침 API"""
try:
analyzer = AdvancedAIAnalyzer()
data = analyzer.get_all_data(force_refresh=True)
return jsonify({
'success': True,
'message': '데이터가 성공적으로 갱신되었습니다',
'stats': data['stats']
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/health')
def health():
"""헬스 체크"""
try:
# DB 연결 확인
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM news")
news_count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM models")
models_count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM spaces")
spaces_count = cursor.fetchone()[0]
conn.close()
return jsonify({
"status": "healthy",
"service": "AI News LLM Analyzer",
"version": "3.2.0",
"database": {
"connected": True,
"news_count": news_count,
"models_count": models_count,
"spaces_count": spaces_count
},
"fireworks_api": {
"configured": bool(os.environ.get('FIREWORKS_API_KEY'))
},
"timestamp": datetime.now().isoformat()
})
except Exception as e:
return jsonify({
"status": "unhealthy",
"error": str(e)
}), 500
# ============================================
# 메인 실행
# ============================================
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
print(f"""
╔════════════════════════════════════════════════════════════╗
║ ║
║ 🤖 AI 뉴스 & 허깅페이스 LLM 분석 웹앱 v3.2 ║
║ ║
╚════════════════════════════════════════════════════════════╝
✨ 주요 기능:
• 💾 SQLite DB 영구 스토리지
• 🌐 AI Times 실시간 뉴스 크롤링 (2개 섹션)
• 📰 뉴스 초등학생 수준 분석
• 🤗 허깅페이스 트렌딩 모델 TOP 30 (모델 카드 분석)
• 🚀 허깅페이스 트렌딩 스페이스 TOP 30 (app.py 분석)
• 🧠 Fireworks AI (Qwen3-235B) 실시간 LLM 분석
• 🎨 탭 UI (뉴스/모델/스페이스)
🔑 API 설정:
FIREWORKS_API_KEY: {"✅ 설정됨" if os.environ.get('FIREWORKS_API_KEY') else "❌ 미설정 (템플릿 모드)"}
🚀 서버 정보:
📍 메인: http://localhost:{port}
🔄 강제갱신: http://localhost:{port}/?refresh=true
📊 API: http://localhost:{port}/api/data
🔥 새로고침 API: http://localhost:{port}/api/refresh
💚 Health: http://localhost:{port}/health
💾 데이터베이스: {DB_PATH}
초기화 중...
""")
# 데이터베이스 초기화
try:
init_database()
except Exception as e:
print(f"❌ DB 초기화 오류: {e}")
sys.exit(1)
print("\n✅ 서버 준비 완료!")
print("브라우저에서 위 URL을 열어주세요!")
print("종료: Ctrl+C\n")
try:
app.run(
host='0.0.0.0',
port=port,
debug=False,
threaded=True
)
except KeyboardInterrupt:
print("\n\n👋 서버 종료!")
sys.exit(0)
except Exception as e:
print(f"\n❌서버 오류: {e}")
sys.exit(1)