Download app.py from muzsang/Notions: direct link, hf CLI and curl.
- Browser
- Download file 18.1 kB
-
https://huggingface.co/spaces/muzsang/Notions/resolve/main/app.py
- Command line
-
hf download hf://spaces/muzsang/Notions/app.py
-
curl -L -o app.py https://huggingface.co/spaces/muzsang/Notions/resolve/main/app.py
18.1 kB
| import uuid | |
| import json | |
| import datetime | |
| import time | |
| import os | |
| import secrets | |
| import urllib.request | |
| import urllib.parse | |
| import urllib.error | |
| import ssl | |
| from typing import Optional, Dict, List, Iterator, Union | |
| from dataclasses import dataclass, asdict | |
| from enum import Enum | |
| from flask import Flask, request, jsonify, Response | |
| from functools import wraps | |
| # 模型枚举 | |
| class NotionAIModel(Enum): | |
| ANTHROPIC_SONNET_4 = "anthropic-sonnet-4" | |
| ANTHROPIC_OPUS_4 = "anthropic-opus-4" | |
| OPENAI_GPT_4_1 = "openai-gpt-4.1" | |
| def list_models(cls): | |
| return [model.value for model in cls] | |
| # API密钥认证装饰器 | |
| def require_api_key(f): | |
| def decorated_function(*args, **kwargs): | |
| api_key = None | |
| auth_header = request.headers.get('Authorization') | |
| if auth_header and auth_header.startswith('Bearer '): | |
| api_key = auth_header[7:] | |
| if not api_key: | |
| api_key = request.headers.get('X-API-Key') | |
| if not api_key: | |
| api_key = request.args.get('api_key') | |
| if not api_key: | |
| return jsonify({ | |
| "error": { | |
| "message": "No API key provided", | |
| "type": "authentication_error", | |
| "code": "no_api_key" | |
| } | |
| }), 401 | |
| valid_api_keys = get_valid_api_keys() | |
| if not valid_api_keys or not verify_api_key(api_key, valid_api_keys): | |
| return jsonify({ | |
| "error": { | |
| "message": "Invalid API key provided.", | |
| "type": "authentication_error", | |
| "code": "invalid_api_key" | |
| } | |
| }), 401 | |
| return f(*args, **kwargs) | |
| return decorated_function | |
| def get_valid_api_keys(): | |
| api_keys_env = os.getenv("API_KEYS", "") | |
| if not api_keys_env: | |
| return [] | |
| return [key.strip() for key in api_keys_env.split(",") if key.strip()] | |
| def verify_api_key(provided_key: str, valid_keys: List[str]) -> bool: | |
| return provided_key in valid_keys | |
| def generate_api_key() -> str: | |
| return f"sk-{secrets.token_urlsafe(32)}" | |
| # Notion API 相关 | |
| NOTION_API_URL = "<https://www.notion.so/api/v3/runInferenceTranscript>" | |
| def generate_iso_time_with_offset(): | |
| now_local = datetime.datetime.now().astimezone() | |
| return now_local.isoformat(timespec='milliseconds') | |
| def make_notion_request(url, headers, payload): | |
| """使用 urllib 发送请求 - 修复版本""" | |
| try: | |
| print(f"🔗 Making urllib request to: {url}") | |
| # 准备数据 | |
| data = json.dumps(payload).encode('utf-8') | |
| # 创建请求 | |
| req = urllib.request.Request(url, data=data, headers=headers, method='POST') | |
| # 创建SSL上下文 | |
| ctx = ssl.create_default_context() | |
| print(f"📡 Sending {len(data)} bytes...") | |
| # 发送请求 | |
| with urllib.request.urlopen(req, context=ctx, timeout=120) as response: | |
| print(f"📊 Response status: {response.getcode()}") | |
| if response.getcode() != 200: | |
| error_data = response.read().decode('utf-8') | |
| print(f"❌ Non-200 response: {error_data[:500]}...") | |
| raise Exception(f"HTTP {response.getcode()}: {error_data}") | |
| # 读取完整响应 | |
| response_text = response.read().decode('utf-8') | |
| print(f"📦 Raw response length: {len(response_text)} chars") | |
| # 使用你的解析方式 | |
| full_response = "" | |
| # 处理NDJSON格式 - 参考你的成功代码 | |
| 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 | |
| print(f"✅ Response completed: {len(full_response)} chars") | |
| return { | |
| "success": True, | |
| "response": full_response | |
| } | |
| except Exception as e: | |
| print(f"❌ Request failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return { | |
| "success": False, | |
| "error": str(e) | |
| } | |
| def call_notion_ai_original( | |
| notion_full_cookie: str, | |
| space_id: str, | |
| user_id: str, | |
| user_message_text: str, | |
| system_prompt_text: str = "You are a helpful AI assistant.", | |
| ai_model_name: str = "anthropic-sonnet-4", | |
| use_websearch_flag: bool = False, | |
| thread_id_to_use: str = None, | |
| existing_transcript_history: list = None, | |
| generate_title_flag: bool = True, | |
| default_space_view_id: str = "1fe9d245-4798-81de-bcd1-0006169c8e8b", | |
| default_user_name_base: str = "User"): | |
| print(f"🚀 Notion AI call starting...") | |
| print(f" Message: {user_message_text[:100]}...") | |
| print(f" Model: {ai_model_name}") | |
| trace_id = str(uuid.uuid4()) | |
| current_datetime_iso = generate_iso_time_with_offset() | |
| is_new_thread_request = not bool(thread_id_to_use) | |
| if is_new_thread_request: | |
| thread_id_for_request = str(uuid.uuid4()) | |
| print(f"📝 Generated new Thread ID: {thread_id_for_request}") | |
| else: | |
| thread_id_for_request = thread_id_to_use | |
| # 构建transcript - 参考你的成功结构 | |
| transcript = [] | |
| # 配置 | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "config", | |
| "value": { | |
| "type": "markdown-chat", | |
| "model": ai_model_name, | |
| "useWebsearch": use_websearch_flag | |
| } | |
| }) | |
| # 系统提示 - 使用你的方式 | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "context", | |
| "value": { | |
| "userName": system_prompt_text # 直接使用系统提示,而不是复杂的格式 | |
| } | |
| }) | |
| # 添加历史记录 | |
| if existing_transcript_history: | |
| for msg in existing_transcript_history: | |
| if msg["role"] == "user": | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "user", | |
| "value": [[msg["content"]]] | |
| }) | |
| elif msg["role"] == "assistant": | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "ai", # 使用 "ai" 而不是 "markdown-chat" | |
| "value": [[msg["content"]]] | |
| }) | |
| # 添加当前用户消息 | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "user", | |
| "value": [[user_message_text]] | |
| }) | |
| # 构建payload - 简化版本,参考你的成功代码 | |
| payload = { | |
| "traceId": trace_id, | |
| "spaceId": space_id, | |
| "transcript": transcript, | |
| "createThread": False, # 改为False | |
| "debugOverrides": { | |
| "cachedInferences": {}, | |
| "annotationInferences": {}, | |
| "emitInferences": False | |
| }, | |
| "generateTitle": False, # 改为False | |
| "saveAllThreadOperations": False # 改为False | |
| } | |
| # 简化headers | |
| headers = { | |
| "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", | |
| "Accept": "application/x-ndjson", | |
| "Content-Type": "application/json", | |
| "Cookie": notion_full_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-space-id": space_id | |
| } | |
| print(f"📡 Sending request to Notion API...") | |
| print(f" Payload size: {len(json.dumps(payload))} chars") | |
| # 使用修复的请求方法 | |
| result = make_notion_request(NOTION_API_URL, headers, payload) | |
| if result["success"]: | |
| ai_response = result["response"] | |
| return { | |
| "ai_response": ai_response, | |
| "thread_id": thread_id_for_request, | |
| "updated_transcript_history": existing_transcript_history or [], | |
| "title": None, | |
| "error": None | |
| } | |
| else: | |
| return { | |
| "ai_response": None, | |
| "thread_id": thread_id_for_request, | |
| "updated_transcript_history": [], | |
| "title": None, | |
| "error": result["error"] | |
| } | |
| # Flask应用 | |
| app = Flask(__name__) | |
| # CORS支持 | |
| def after_request(response): | |
| response.headers.add('Access-Control-Allow-Origin', '*') | |
| response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') | |
| response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') | |
| return response | |
| def get_config(): | |
| cookie = os.getenv("NOTION_COOKIE") | |
| space_id = os.getenv("NOTION_SPACE_ID") | |
| user_id = os.getenv("NOTION_USER_ID") | |
| space_view_id = os.getenv("NOTION_SPACE_VIEW_ID", "1fe9d245-4798-81de-bcd1-0006169c8e8b") | |
| user_name_base = os.getenv("NOTION_USER_NAME_BASE", "User") | |
| if not all([cookie, space_id, user_id]): | |
| missing = [] | |
| if not cookie: missing.append("NOTION_COOKIE") | |
| if not space_id: missing.append("NOTION_SPACE_ID") | |
| if not user_id: missing.append("NOTION_USER_ID") | |
| raise ValueError(f"Missing required environment variables: {', '.join(missing)}") | |
| return { | |
| "cookie": cookie, | |
| "space_id": space_id, | |
| "user_id": user_id, | |
| "space_view_id": space_view_id, | |
| "user_name_base": user_name_base | |
| } | |
| # 初始化配置 | |
| try: | |
| config = get_config() | |
| print("✅ Configuration loaded successfully") | |
| except ValueError as e: | |
| print(f"❌ Configuration error: {e}") | |
| config = None | |
| def home(): | |
| return jsonify({ | |
| "service": "Notion AI to OpenAI Compatible API", | |
| "status": "running", | |
| "configuration": "configured" if config else "not_configured", | |
| "api_keys": len(get_valid_api_keys()), | |
| "models": NotionAIModel.list_models() | |
| }) | |
| def generate_new_api_key(): | |
| new_key = generate_api_key() | |
| return jsonify({ | |
| "api_key": new_key, | |
| "note": "Add this to your API_KEYS environment variable" | |
| }) | |
| def list_models(): | |
| models_data = [] | |
| for model_value in NotionAIModel.list_models(): | |
| models_data.append({ | |
| "id": model_value, | |
| "object": "model", | |
| "created": int(time.time()), | |
| "owned_by": "notion" | |
| }) | |
| return jsonify({ | |
| "object": "list", | |
| "data": models_data | |
| }) | |
| def chat_completions_options(): | |
| """处理CORS预检请求""" | |
| response = jsonify({}) | |
| response.headers.add('Access-Control-Allow-Origin', '*') | |
| response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') | |
| response.headers.add('Access-Control-Allow-Methods', 'POST,OPTIONS') | |
| return response | |
| def chat_completions(): | |
| print("💬 Chat completions endpoint called") | |
| if not config: | |
| return jsonify({"error": "Service not configured"}), 500 | |
| try: | |
| request_data = request.get_json() | |
| if not request_data or not request_data.get("messages"): | |
| return jsonify({ | |
| "error": { | |
| "message": "Missing 'messages' field", | |
| "type": "invalid_request_error" | |
| } | |
| }), 400 | |
| messages = request_data.get("messages", []) | |
| model = request_data.get("model", "anthropic-sonnet-4") | |
| stream = request_data.get("stream", False) | |
| conversation_id = request_data.get("conversation_id", str(uuid.uuid4())) | |
| print(f"📝 Model: {model}, Stream: {stream}, Conversation: {conversation_id}") | |
| # 提取系统提示和用户消息 | |
| system_prompt = "You are a helpful AI assistant." | |
| conversation_messages = [] | |
| for msg in messages: | |
| if msg["role"] == "system": | |
| system_prompt = msg["content"] | |
| elif msg["role"] in ["user", "assistant"]: | |
| conversation_messages.append(msg) | |
| # 获取最后一条用户消息 | |
| if not conversation_messages or conversation_messages[-1]["role"] != "user": | |
| return jsonify({ | |
| "error": { | |
| "message": "No user message found", | |
| "type": "invalid_request_error" | |
| } | |
| }), 400 | |
| last_user_message = conversation_messages[-1]["content"] | |
| # 构建历史记录 - 使用你的格式 | |
| transcript_history = [] | |
| if len(conversation_messages) > 1: | |
| for msg in conversation_messages[:-1]: | |
| transcript_history.append({ | |
| "role": msg["role"], | |
| "content": msg["content"] | |
| }) | |
| print(f"🎯 Processing message: {last_user_message[:100]}...") | |
| # 调用Notion AI | |
| response_data = call_notion_ai_original( | |
| notion_full_cookie=config["cookie"], | |
| space_id=config["space_id"], | |
| user_id=config["user_id"], | |
| user_message_text=last_user_message, | |
| system_prompt_text=system_prompt, | |
| ai_model_name=model, | |
| use_websearch_flag=False, | |
| thread_id_to_use=None, | |
| existing_transcript_history=transcript_history, | |
| generate_title_flag=False, | |
| default_space_view_id=config["space_view_id"], | |
| default_user_name_base=config["user_name_base"] | |
| ) | |
| if response_data and not response_data.get("error"): | |
| ai_response = response_data.get("ai_response", "") | |
| print(f"✅ AI response received: {len(ai_response)} chars") | |
| if stream: | |
| # 使用你的成功流式响应格式 | |
| def generate(): | |
| # 发送开始标记 | |
| 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" | |
| # 分块发送内容 | |
| chunk_size = 50 | |
| for i in range(0, len(ai_response), chunk_size): | |
| content = ai_response[i:i + chunk_size] | |
| 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" | |
| time.sleep(0.01) | |
| # 发送结束标记 | |
| 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', # 使用正确的SSE类型 | |
| headers={ | |
| 'Cache-Control': 'no-cache', | |
| 'Connection': 'keep-alive', | |
| 'Access-Control-Allow-Origin': '*' | |
| } | |
| ) | |
| else: | |
| # 非流式响应 | |
| return jsonify({ | |
| "id": conversation_id, | |
| "object": "chat.completion", | |
| "created": int(time.time()), | |
| "model": model, | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "message": { | |
| "role": "assistant", | |
| "content": ai_response | |
| }, | |
| "finish_reason": "stop" | |
| } | |
| ], | |
| "usage": { | |
| "prompt_tokens": -1, | |
| "completion_tokens": -1, | |
| "total_tokens": -1 | |
| } | |
| }) | |
| else: | |
| error_msg = response_data.get("error", "Unknown error") if response_data else "No response" | |
| print(f"❌ Notion AI error: {error_msg}") | |
| return jsonify({ | |
| "error": { | |
| "message": error_msg, | |
| "type": "api_error" | |
| } | |
| }), 500 | |
| except Exception as e: | |
| print(f"❌ Error in chat completions: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return jsonify({ | |
| "error": { | |
| "message": str(e), | |
| "type": "internal_server_error" | |
| } | |
| }), 500 | |
| def health_check(): | |
| return jsonify({ | |
| "status": "healthy", | |
| "timestamp": int(time.time()), | |
| "configured": config is not None, | |
| "api_keys_configured": bool(get_valid_api_keys()) | |
| }) | |
| if __name__ == "__main__": | |
| port = int(os.getenv("PORT", 7860)) | |
| api_keys = get_valid_api_keys() | |
| if not api_keys: | |
| print("⚠️ WARNING: No API keys configured") | |
| else: | |
| print(f"✅ API authentication configured with {len(api_keys)} key(s)") | |
| app.run(host='0.0.0.0', port=port, debug=False) | |