Download app.py from muzsang/Notion: direct link, hf CLI and curl.
- Browser
- Download file 22.7 kB
-
https://huggingface.co/spaces/muzsang/Notion/resolve/main/app.py
- Command line
-
hf download hf://spaces/muzsang/Notion/app.py
-
curl -L -o app.py https://huggingface.co/spaces/muzsang/Notion/resolve/main/app.py
22.7 kB
| import os | |
| import json | |
| import uuid | |
| import logging | |
| import time | |
| from datetime import datetime | |
| from flask import Flask, request, jsonify, Response | |
| from functools import wraps | |
| # 强制重新初始化 requests | |
| try: | |
| import requests | |
| from requests.adapters import HTTPAdapter | |
| from requests.packages.urllib3.util.retry import Retry | |
| # 创建一个新的 session 并手动配置适配器 | |
| def create_requests_session(): | |
| session = requests.Session() | |
| # 创建重试策略 | |
| retry_strategy = Retry( | |
| total=3, | |
| status_forcelist=[429, 500, 502, 503, 504], | |
| method_whitelist=["HEAD", "GET", "OPTIONS", "POST"] | |
| ) | |
| # 创建适配器 | |
| adapter = HTTPAdapter(max_retries=retry_strategy) | |
| # 挂载适配器 | |
| session.mount("http://", adapter) | |
| session.mount("https://", adapter) | |
| return session | |
| # 全局 session | |
| HTTP_SESSION = create_requests_session() | |
| REQUESTS_AVAILABLE = True | |
| logger = logging.getLogger(__name__) | |
| logger.info("✅ Requests 库已成功初始化") | |
| except ImportError as e: | |
| logger.error(f"❌ Requests 库导入失败: {e}") | |
| REQUESTS_AVAILABLE = False | |
| HTTP_SESSION = None | |
| # 如果 requests 不可用,使用 urllib | |
| if not REQUESTS_AVAILABLE: | |
| import urllib.request | |
| import urllib.parse | |
| import ssl | |
| # 设置日志 | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.StreamHandler() | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Notion AI 模型列表 | |
| NOTION_MODELS = { | |
| "openai-gpt-4.1": "GPT-4.1", | |
| "anthropic-sonnet-4": "Claude Sonnet 4", | |
| "anthropic-opus-4": "Claude Opus 4", | |
| "anthropic-sonnet-3.7": "Claude 3.7 Sonnet" | |
| } | |
| # 全局配置 | |
| class Config: | |
| # 从环境变量读取认证信息 | |
| NOTION_COOKIE = os.environ.get('NOTION_COOKIE', '') | |
| NOTION_SPACE_ID = os.environ.get('NOTION_SPACE_ID', '') | |
| USER_AGENT = os.environ.get('USER_AGENT', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0') | |
| # API URL | |
| NOTION_API_URL = os.environ.get('NOTION_API_URL', '<https://www.notion.so/api/v3/runInferenceTranscript>') | |
| # 默认模型 | |
| DEFAULT_MODEL = os.environ.get('DEFAULT_MODEL', 'anthropic-opus-4') | |
| # 超时设置 | |
| REQUEST_TIMEOUT = int(os.environ.get('REQUEST_TIMEOUT', 120)) | |
| # 服务器设置 | |
| HOST = os.environ.get('HOST', '0.0.0.0') | |
| PORT = int(os.environ.get('PORT', 7860)) | |
| # 系统提示词设置 | |
| EMPTY_SYSTEM_PROMPT = os.environ.get('EMPTY_SYSTEM_PROMPT', '你是一个乐于助人的AI助手。') | |
| # API 密钥认证 | |
| API_KEYS = os.environ.get('API_KEYS', '').split(',') | |
| REQUIRE_API_KEY = os.environ.get('REQUIRE_API_KEY', 'true').lower() == 'true' | |
| # 保存对话历史的类 | |
| class ConversationManager: | |
| def __init__(self): | |
| self.conversations = {} | |
| def create_conversation(self, conversation_id=None): | |
| if conversation_id is None: | |
| conversation_id = str(uuid.uuid4()) | |
| self.conversations[conversation_id] = { | |
| "trace_id": str(uuid.uuid4()), | |
| "messages": [], | |
| "system_prompt": Config.EMPTY_SYSTEM_PROMPT, | |
| "model": Config.DEFAULT_MODEL | |
| } | |
| return conversation_id | |
| def get_conversation(self, conversation_id): | |
| if conversation_id not in self.conversations: | |
| conversation_id = self.create_conversation(conversation_id) | |
| return self.conversations[conversation_id] | |
| def add_message(self, conversation_id, role, content): | |
| conversation = self.get_conversation(conversation_id) | |
| message = { | |
| "id": str(uuid.uuid4()), | |
| "role": role, | |
| "content": content, | |
| "timestamp": datetime.now().astimezone().isoformat(timespec='milliseconds') | |
| } | |
| conversation["messages"].append(message) | |
| return message | |
| def set_system_prompt(self, conversation_id, system_prompt): | |
| conversation = self.get_conversation(conversation_id) | |
| conversation["system_prompt"] = system_prompt if system_prompt else Config.EMPTY_SYSTEM_PROMPT | |
| return conversation | |
| def set_model(self, conversation_id, model): | |
| if model not in NOTION_MODELS: | |
| raise ValueError(f"不支持的模型: {model}") | |
| conversation = self.get_conversation(conversation_id) | |
| conversation["model"] = model | |
| return conversation | |
| def get_transcript(self, conversation_id): | |
| conversation = self.get_conversation(conversation_id) | |
| current_datetime_iso = datetime.now().astimezone().isoformat(timespec='milliseconds') | |
| transcript = [ | |
| { | |
| "id": str(uuid.uuid4()), | |
| "type": "config", | |
| "value": { | |
| "type": "markdown-chat", | |
| "model": conversation["model"], | |
| "useWebsearch": True | |
| } | |
| } | |
| ] | |
| system_prompt = conversation["system_prompt"] | |
| user_name = f"Niigata\\n\\nNote: {system_prompt}" if system_prompt and system_prompt.strip() else "Niigata" | |
| user_id = "" | |
| if 'notion_user_id=' in Config.NOTION_COOKIE: | |
| user_id = Config.NOTION_COOKIE.split('notion_user_id=')[1].split(';')[0] | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "context", | |
| "value": { | |
| "timezone": "Asia/Shanghai", | |
| "userName": user_name, | |
| "userId": user_id, | |
| "spaceName": "Linux Do", | |
| "spaceId": Config.NOTION_SPACE_ID, | |
| "spaceViewId": Config.NOTION_SPACE_ID, | |
| "currentDatetime": current_datetime_iso, | |
| "surface": "api_call" | |
| } | |
| }) | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "recordPointers": [], | |
| "type": "agent-integration" | |
| }) | |
| for msg in conversation["messages"]: | |
| if msg["role"] == "user": | |
| transcript.append({ | |
| "id": msg["id"], | |
| "type": "user", | |
| "value": [[msg["content"]]], | |
| "userId": user_id, | |
| "createdAt": msg.get("timestamp", current_datetime_iso) | |
| }) | |
| elif msg["role"] == "assistant": | |
| transcript.append({ | |
| "id": msg["id"], | |
| "type": "markdown-chat", | |
| "value": msg["content"], | |
| "traceId": conversation["trace_id"] | |
| }) | |
| return transcript | |
| def delete_conversation(self, conversation_id): | |
| if conversation_id in self.conversations: | |
| del self.conversations[conversation_id] | |
| return True | |
| return False | |
| # HTTP 客户端类(支持 requests 和 urllib) | |
| class HTTPClient: | |
| def post_json_with_requests(url, headers, data, timeout=120, stream=False): | |
| """使用 requests 发送请求""" | |
| try: | |
| logger.info(f"🔄 使用 requests 发送请求到: {url}") | |
| if HTTP_SESSION is None: | |
| logger.error("❌ HTTP_SESSION 未初始化") | |
| return None | |
| response = HTTP_SESSION.post( | |
| url, | |
| headers=headers, | |
| json=data, | |
| timeout=timeout, | |
| stream=stream | |
| ) | |
| logger.info(f"✅ Requests 响应状态: {response.status_code}") | |
| if response.status_code != 200: | |
| logger.error(f"❌ 请求失败: {response.status_code}") | |
| logger.error(f"响应内容: {response.text}") | |
| return None | |
| if stream: | |
| return response | |
| else: | |
| return response.text | |
| except Exception as e: | |
| logger.error(f"❌ Requests 请求失败: {str(e)}") | |
| import traceback | |
| logger.error(traceback.format_exc()) | |
| return None | |
| def post_json_with_urllib(url, headers, data, timeout=120): | |
| """使用 urllib 发送请求""" | |
| try: | |
| logger.info(f"🔄 使用 urllib 发送请求到: {url}") | |
| json_data = json.dumps(data).encode('utf-8') | |
| req = urllib.request.Request(url, data=json_data, method='POST') | |
| for key, value in headers.items(): | |
| req.add_header(key, value) | |
| context = ssl.create_default_context() | |
| with urllib.request.urlopen(req, timeout=timeout, context=context) as response: | |
| logger.info(f"✅ Urllib 响应状态: {response.status}") | |
| if response.status != 200: | |
| error_text = response.read().decode('utf-8') | |
| logger.error(f"❌ 请求失败: {error_text}") | |
| return None | |
| response_data = response.read().decode('utf-8') | |
| return response_data | |
| except Exception as e: | |
| logger.error(f"❌ Urllib 请求失败: {str(e)}") | |
| import traceback | |
| logger.error(traceback.format_exc()) | |
| return None | |
| def post_json(url, headers, data, timeout=120, stream=False): | |
| """智能选择 HTTP 客户端""" | |
| # 首先尝试 requests | |
| if REQUESTS_AVAILABLE and stream: | |
| result = HTTPClient.post_json_with_requests(url, headers, data, timeout, stream=True) | |
| if result is not None: | |
| return result | |
| # 如果 requests 失败或不需要流式,使用 urllib | |
| if not stream: | |
| result = HTTPClient.post_json_with_urllib(url, headers, data, timeout) | |
| if result is not None: | |
| return result | |
| # 最后尝试 requests 非流式 | |
| if REQUESTS_AVAILABLE: | |
| result = HTTPClient.post_json_with_requests(url, headers, data, timeout, stream=False) | |
| if result is not None: | |
| return result | |
| logger.error("❌ 所有 HTTP 客户端都失败了") | |
| return None | |
| # Notion API 调用类 | |
| class NotionAIClient: | |
| def get_headers(): | |
| return { | |
| 'User-Agent': Config.USER_AGENT, | |
| 'Accept': 'application/x-ndjson', | |
| 'Content-Type': 'application/json', | |
| 'Cookie': Config.NOTION_COOKIE, | |
| 'notion-audit-log-platform': 'web', | |
| 'notion-client-version': '23.13.0.3598', | |
| 'origin': '<https://www.notion.so>', | |
| 'referer': '<https://www.notion.so/>', | |
| 'x-notion-active-user-header': Config.NOTION_COOKIE.split('notion_user_id=')[1].split(';')[0] if 'notion_user_id=' in Config.NOTION_COOKIE else '', | |
| 'x-notion-space-id': Config.NOTION_SPACE_ID | |
| } | |
| def get_request_body(conversation_id, conversation_manager): | |
| conversation = conversation_manager.get_conversation(conversation_id) | |
| return { | |
| "traceId": conversation["trace_id"], | |
| "spaceId": Config.NOTION_SPACE_ID, | |
| "transcript": conversation_manager.get_transcript(conversation_id), | |
| "threadId": conversation_id, | |
| "createThread": True, | |
| "generateTitle": True, | |
| "saveAllThreadOperations": True, | |
| "threadParentPointer": { | |
| "table": "space", | |
| "id": Config.NOTION_SPACE_ID, | |
| "spaceId": Config.NOTION_SPACE_ID | |
| } | |
| } | |
| def generate_completion(conversation_id, conversation_manager, stream=True): | |
| headers = NotionAIClient.get_headers() | |
| body = NotionAIClient.get_request_body(conversation_id, conversation_manager) | |
| logger.info(f"🚀 发送请求到 Notion API,对话ID: {conversation_id}") | |
| logger.debug(f"请求体: {json.dumps(body, ensure_ascii=False)}") | |
| # 使用智能 HTTP 客户端 | |
| response = HTTPClient.post_json( | |
| Config.NOTION_API_URL, | |
| headers, | |
| body, | |
| Config.REQUEST_TIMEOUT, | |
| stream=stream | |
| ) | |
| if response is None: | |
| logger.error("❌ 所有 HTTP 方法都失败了") | |
| return None | |
| # 如果是流式响应对象,直接返回 | |
| if hasattr(response, 'iter_content'): | |
| return response | |
| # 如果是文本响应,解析后返回 | |
| if isinstance(response, str): | |
| if stream: | |
| # 创建一个模拟的流式响应 | |
| class MockStreamResponse: | |
| def __init__(self, text): | |
| self.text = text | |
| self.status_code = 200 | |
| def iter_content(self, chunk_size=1024): | |
| text_bytes = self.text.encode('utf-8') | |
| for i in range(0, len(text_bytes), chunk_size): | |
| yield text_bytes[i:i+chunk_size] | |
| return MockStreamResponse(response) | |
| else: | |
| return NotionAIClient.parse_response(response) | |
| return None | |
| def parse_response(response_text): | |
| full_response = "" | |
| lines = response_text.replace('[', '').replace(']', '').split('\\n') | |
| for line in lines: | |
| line = line.strip() | |
| if not line or line == ',' or line == '[' or line == ']': | |
| continue | |
| if line.endswith(','): | |
| line = line[:-1] | |
| try: | |
| json_obj = json.loads(line) | |
| if isinstance(json_obj, dict) and json_obj.get('type') == 'markdown-chat' and 'value' in json_obj: | |
| content = json_obj.get('value', '') | |
| full_response += content | |
| except json.JSONDecodeError: | |
| pass | |
| return full_response | |
| # 创建Flask应用 | |
| app = Flask(__name__) | |
| conversation_manager = ConversationManager() | |
| # API密钥验证装饰器 | |
| def require_api_key(f): | |
| def decorated_function(*args, **kwargs): | |
| if not Config.REQUIRE_API_KEY: | |
| return f(*args, **kwargs) | |
| api_key = request.headers.get('Authorization') | |
| if api_key: | |
| api_key = api_key.replace('Bearer ', '') | |
| if not api_key or (Config.API_KEYS and api_key not in Config.API_KEYS): | |
| return jsonify({ | |
| "error": { | |
| "message": "Invalid API key", | |
| "type": "invalid_request_error", | |
| "code": "invalid_api_key" | |
| } | |
| }), 401 | |
| return f(*args, **kwargs) | |
| return decorated_function | |
| # 路由定义 | |
| def index(): | |
| http_status = "✅ Requests 可用" if REQUESTS_AVAILABLE else "⚠️ 仅 Urllib 可用" | |
| return f""" | |
| <html> | |
| <head> | |
| <title>Notion AI API (OpenAI Compatible)</title> | |
| <style> | |
| body {{ | |
| font-family: Arial, sans-serif; | |
| max-width: 800px; | |
| margin: 0 auto; | |
| padding: 20px; | |
| line-height: 1.6; | |
| }} | |
| .status {{ | |
| background: #e8f5e8; | |
| padding: 15px; | |
| border-radius: 5px; | |
| margin-bottom: 20px; | |
| }} | |
| .models {{ | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| margin-top: 10px; | |
| }} | |
| .model {{ | |
| background: #e9f5ff; | |
| padding: 8px 12px; | |
| border-radius: 4px; | |
| font-family: monospace; | |
| }} | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Notion AI API 服务</h1> | |
| <div class="status"> | |
| {http_status}<br> | |
| 服务运行正常 | |
| </div> | |
| <h2>可用模型</h2> | |
| <div class="models"> | |
| <div class="model">openai-gpt-4.1</div> | |
| <div class="model">anthropic-sonnet-4</div> | |
| <div class="model">anthropic-opus-4</div> | |
| <div class="model">anthropic-sonnet-3.7</div> | |
| </div> | |
| <h2>测试端点</h2> | |
| <p><strong>健康检查:</strong> <a href="/health">/health</a></p> | |
| <p><strong>模型列表:</strong> <a href="/v1/models">/v1/models</a></p> | |
| <p><strong>聊天完成:</strong> POST /v1/chat/completions</p> | |
| </body> | |
| </html> | |
| """ | |
| def health_check(): | |
| return jsonify({ | |
| "status": "ok", | |
| "version": "3.0.0", | |
| "http_client": "requests+urllib" if REQUESTS_AVAILABLE else "urllib_only", | |
| "requests_available": REQUESTS_AVAILABLE, | |
| "models": list(NOTION_MODELS.keys()), | |
| "config": { | |
| "cookie_configured": bool(Config.NOTION_COOKIE), | |
| "space_id_configured": bool(Config.NOTION_SPACE_ID) | |
| } | |
| }) | |
| def list_models(): | |
| models = [] | |
| for model_id, model_name in NOTION_MODELS.items(): | |
| models.append({ | |
| "id": model_id, | |
| "object": "model", | |
| "created": int(time.time()), | |
| "owned_by": "notion" | |
| }) | |
| return jsonify({"object": "list", "data": models}) | |
| def create_chat_completion(): | |
| try: | |
| data = request.json | |
| model = data.get('model', Config.DEFAULT_MODEL) | |
| messages = data.get('messages', []) | |
| stream = data.get('stream', False) | |
| conversation_id = data.get('conversation_id', str(uuid.uuid4())) | |
| if model not in NOTION_MODELS: | |
| return jsonify({ | |
| "error": { | |
| "message": f"Model {model} does not exist", | |
| "type": "invalid_request_error", | |
| "code": "model_not_found" | |
| } | |
| }), 404 | |
| conversation_manager.set_model(conversation_id, model) | |
| system_message = None | |
| for msg in messages: | |
| role = msg.get('role') | |
| content = msg.get('content', '') | |
| if role == 'system': | |
| system_message = content | |
| elif role in ['user', 'assistant']: | |
| conversation_manager.add_message(conversation_id, role, content) | |
| conversation_manager.set_system_prompt(conversation_id, system_message) | |
| if stream: | |
| def generate(): | |
| response = NotionAIClient.generate_completion(conversation_id, conversation_manager, stream=True) | |
| if not response: | |
| yield f"data: {json.dumps({'error': 'Failed to generate completion'})}\\n\\n" | |
| return | |
| yield f"data: {json.dumps({'id': conversation_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': model, 'choices': [{'index': 0, 'delta': {'role': 'assistant'}, 'finish_reason': None}]})}\\n\\n" | |
| full_response = "" | |
| for chunk in response.iter_content(chunk_size=1024): | |
| if chunk: | |
| try: | |
| chunk_str = chunk.decode('utf-8', errors='replace') | |
| lines = chunk_str.replace('[', '').replace(']', '').split('\\n') | |
| for line in lines: | |
| line = line.strip() | |
| if not line or line == ',' or line == '[' or line == ']': | |
| continue | |
| if line.endswith(','): | |
| line = line[:-1] | |
| try: | |
| json_obj = json.loads(line) | |
| if isinstance(json_obj, dict) and json_obj.get('type') == 'markdown-chat' and 'value' in json_obj: | |
| content = json_obj.get('value', '') | |
| full_response += content | |
| yield f"data: {json.dumps({'id': conversation_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': model, 'choices': [{'index': 0, 'delta': {'content': content}, 'finish_reason': None}]})}\\n\\n" | |
| except json.JSONDecodeError: | |
| pass | |
| except Exception as e: | |
| logger.warning(f"处理响应块时出错: {str(e)}") | |
| if full_response: | |
| conversation_manager.add_message(conversation_id, "assistant", full_response) | |
| yield f"data: {json.dumps({'id': conversation_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': model, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\\n\\n" | |
| yield "data: [DONE]\\n\\n" | |
| return Response( | |
| generate(), | |
| mimetype='text/event-stream', | |
| headers={'Cache-Control': 'no-cache', 'Connection': 'keep-alive'} | |
| ) | |
| else: | |
| response = NotionAIClient.generate_completion(conversation_id, conversation_manager, stream=False) | |
| if not response: | |
| return jsonify({ | |
| "error": { | |
| "message": "Failed to generate completion", | |
| "type": "server_error", | |
| "code": "internal_error" | |
| } | |
| }), 500 | |
| conversation_manager.add_message(conversation_id, "assistant", response) | |
| return jsonify({ | |
| "id": conversation_id, | |
| "object": "chat.completion", | |
| "created": int(time.time()), | |
| "model": model, | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "message": { | |
| "role": "assistant", | |
| "content": response | |
| }, | |
| "finish_reason": "stop" | |
| } | |
| ], | |
| "usage": { | |
| "prompt_tokens": -1, | |
| "completion_tokens": -1, | |
| "total_tokens": -1 | |
| } | |
| }) | |
| except Exception as e: | |
| logger.error(f"处理请求时出错: {str(e)}", exc_info=True) | |
| return jsonify({ | |
| "error": { | |
| "message": str(e), | |
| "type": "server_error", | |
| "code": "internal_error" | |
| } | |
| }), 500 | |
| if __name__ == "__main__": | |
| if not Config.NOTION_COOKIE or not Config.NOTION_SPACE_ID: | |
| logger.warning("警告: 未设置 NOTION_COOKIE 或 NOTION_SPACE_ID 环境变量") | |
| logger.info(f"🚀 启动服务... (Requests可用: {REQUESTS_AVAILABLE})") | |
| app.run(host=Config.HOST, port=Config.PORT) | |