# -*- coding: utf-8 -*- from flask import Flask, render_template_string, jsonify, request import requests import json from datetime import datetime, timedelta 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 생태계의 핵심 100가지를 한눈에 확인하세요.
최신 뉴스·모델·서비스를 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 탑 100",
"version": "3.3.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 ║
║ ║
╚════════════════════════════════════════════════════════════╝
📌 매일 아침 전 세계 AI 생태계의 핵심 100가지를 한눈에!
최신 뉴스·모델·서비스를 AI가 직접 분석해서 쉽게 설명합니다.
✨ 주요 기능:
• 💾 SQLite DB 영구 스토리지
• 🌐 AI Times 실시간 뉴스 크롤링 (오늘+어제)
• 🔥 Hacker News Top Stories (36시간 이내)
• 📰 뉴스 중고등학생 수준 LLM 분석
• 🤗 허깅페이스 트렌딩 모델 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)