Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
抖音无水印视频文本提取 MCP 服务器
https://github.com/yzfly/douyin-mcp-server
Admin
一个基于 Model Context Protocol (MCP) 的服务器,可以从抖音分享链接下载无水印视频,提取音频并转换为文本。
Tokens:
4,881
Snippets:
15
Trust Score:
8.9
License:
Apache-2.0
Update:
11 months ago
Context
Chat
Benchmark
68
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Local Development Setup for douyin-mcp-server (Bash) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt A set of bash commands to set up the douyin-mcp-server project for local development. Includes cloning the repository, installing dependencies, setting environment variables, and running the server. ```bash # Clone repository git clone https://github.com/yzfly/douyin-mcp-server.git cd douyin-mcp-server # Install in development mode pip install -e . # Set environment variable export DASHSCOPE_API_KEY="sk-your-api-key-here" # Run server directly python -m douyin_mcp_server # Or use the installed command douyin-mcp-server # For Claude Desktop local development # Add to Claude Desktop config: # { # "mcpServers": { # "douyin-mcp": { # "command": "uv", # "args": [ # "run", # "--directory", # "/absolute/path/to/douyin-mcp-server", # "python", # "-m", # "douyin_mcp_server" # ], # "env": { # "DASHSCOPE_API_KEY": "sk-your-api-key" # } # } # } # } ``` -------------------------------- ### Get Douyin Download Link (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Extracts watermark-free download links from Douyin share URLs. This tool does not require API credentials. It takes a Douyin share link as input and returns a JSON object containing the status, video ID, title, download URL, and a usage tip. ```python # Tool invocation example import json # Douyin share link share_text = "https://v.douyin.com/iRNBho6J/" # Call the tool result = get_douyin_download_link(share_link=share_text) result_data = json.loads(result) # Expected output: # { # "status": "success", # "video_id": "7123456789012345678", # "title": "Amazing Video Title", # "download_url": "https://www.iesdouyin.com/aweme/v1/play/?video_id=...", # "description": "Video title: Amazing Video Title", # "usage_tip": "Direct download link for watermark-free video" # } # Error handling if result_data["status"] == "error": print(f"Error: {result_data['error']}") else: download_url = result_data["download_url"] # Use the download_url to fetch the video import requests video_response = requests.get(download_url, stream=True) with open("downloaded_video.mp4", "wb") as f: for chunk in video_response.iter_content(chunk_size=8192): f.write(chunk) ``` -------------------------------- ### Process Douyin Transcription Results (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt This snippet demonstrates how to process the results of a Douyin video transcription. It checks the HTTP status, iterates through transcription results, extracts the transcription URL, and then parses the JSON response to get the full text. It includes basic error handling for missing text content. ```python from http import HTTPStatus import json from urllib import request # Assuming transcription_response is available and contains transcription data # Example structure: # transcription_response = { # "status_code": HTTPStatus.OK, # "output": { # "results": [ # { # "transcription_url": "http://example.com/transcription.json" # } # ] # } # } if transcription_response.status_code == HTTPStatus.OK: for transcription in transcription_response.output['results']: result_url = transcription['transcription_url'] # Use try-except for network request and JSON parsing try: result_data = json.loads(request.urlopen(result_url).read().decode('utf8')) # Extract text if 'transcripts' in result_data and len(result_data['transcripts']) > 0: full_text = result_data['transcripts'][0]['text'] print(f"Transcription: {full_text}") else: print("No text content detected") except Exception as e: print(f"Error processing transcription URL {result_url}: {e}") else: print(f"Transcription failed: {transcription_response.output.message}") ``` -------------------------------- ### DashScope Speech Recognition for Video URLs (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Shows how to use the Alibaba Cloud DashScope API for audio transcription directly from a video URL. It covers setting the API key, initiating an asynchronous transcription task, and waiting for the results. ```python # Direct DashScope API usage import dashscope from http import HTTPStatus import json from urllib import request # Configure API key dashscope.api_key = "sk-your-dashscope-api-key" # Video URL to transcribe video_url = "https://www.iesdouyin.com/aweme/v1/play/?video_id=..." # Start async transcription task task_response = dashscope.audio.asr.Transcription.async_call( model="paraformer-v2", file_urls=[video_url], language_hints=['zh', 'en'] # Support Chinese and English ) # Wait for completion transcription_response = dashscope.audio.asr.Transcription.wait( task=task_response.output.task_id ) ``` -------------------------------- ### Initialize Douyin Processor and Parse Share URL (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Initializes the DouyinProcessor with an API key and model, then parses a Douyin share URL to extract video ID and title. It also demonstrates extracting text content directly from the video URL. Includes error handling and cleanup. ```python import os # Assuming DouyinProcessor is defined elsewhere # from your_module import DouyinProcessor # Initialize processor with API key api_key = os.getenv('DASHSCOPE_API_KEY') processor = DouyinProcessor(api_key=api_key, model="paraformer-v2") try: # Step 1: Parse share URL share_text = "https://v.douyin.com/iRNBho6J/" video_info = processor.parse_share_url(share_text) print(f"Video ID: {video_info['video_id']}") print(f"Title: {video_info['title']}") # Step 2: Extract text directly from video URL (recommended) text_content = processor.extract_text_from_video_url(video_info['url']) print(f"Transcription: {text_content}") # Alternative Step 2: Download video and extract audio (if needed locally) # video_path = await processor.download_video(video_info, ctx) # audio_path = processor.extract_audio(video_path) # processor.cleanup_files(video_path, audio_path) except ValueError as e: print(f"Invalid URL or parsing error: {e}") except Exception as e: print(f"Processing error: {e}") finally: # Cleanup handled automatically by __del__ del processor ``` -------------------------------- ### MCP Server Configuration (JSON) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Provides a JSON configuration snippet for setting up MCP servers, specifically detailing the 'douyin-mcp' server. It includes commands, arguments, and environment variables required for integration. ```json { "mcpServers": { "douyin-mcp": { "command": "uvx", "args": ["douyin-mcp-server"], "env": { "DASHSCOPE_API_KEY": "sk-your-api-key-from-dashscope" } } } } ``` -------------------------------- ### MCP Resource URI Pattern for Douyin Videos (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Demonstrates the structure of a Douyin MCP Resource URI, which is used within MCP-compatible clients to access video information. Shows how to construct the URI and the expected JSON response. ```python # MCP Resource URI pattern: douyin://video/{video_id} # This is used within MCP-compatible clients # Example video ID video_id = "7123456789012345678" # Resource URI resource_uri = f"douyin://video/{video_id}" # When accessed through MCP client, returns: # { # "url": "https://www.iesdouyin.com/aweme/v1/play/?video_id=...", # "title": "Video Description", # "video_id": "7123456789012345678" # } ``` -------------------------------- ### HTTP API Integration for Douyin Videos (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Demonstrates how to interact with Douyin video endpoints using Python's requests library. It shows how to fetch video page data, extract video IDs, and construct clean download URLs by mimicking mobile browser headers. ```python import requests import re import json # Headers mimicking mobile browser HEADERS = { 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1' } # Parse Douyin share link share_url = "https://v.douyin.com/iRNBho6J/" response = requests.get(share_url, headers=HEADERS) video_id = response.url.split("?")[0].strip("/").split("/")[-1] video_page_url = f'https://www.iesdouyin.com/share/video/{video_id}' # Fetch video page page_response = requests.get(video_page_url, headers=HEADERS) page_response.raise_for_status() # Extract video data from JavaScript pattern = re.compile(r"window\._ROUTER_DATA\s*=\s*(.*?)</script>", re.DOTALL) match = pattern.search(page_response.text) if match: json_data = json.loads(match.group(1).strip()) # Navigate JSON structure to find video info # Extract watermark-free URL by replacing 'playwm' with 'play' video_info = json_data["loaderData"]["video_(id)/page"]["videoInfoRes"] video_url = video_info["item_list"][0]["video"]["play_addr"]["url_list"][0] clean_url = video_url.replace("playwm", "play") print(f"Download URL: {clean_url}") ``` -------------------------------- ### Extract Text from Douyin Video (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt Provides an end-to-end pipeline for extracting text content from Douyin videos using AI speech recognition via the Alibaba Cloud DashScope API. It requires the DASHSCOPE_API_KEY to be set in the environment. Inputs include a Douyin share link and an optional model name; outputs the transcribed text. ```python # Async tool usage example import asyncio import os # Configure environment os.environ['DASHSCOPE_API_KEY'] = 'sk-your-dashscope-api-key-here' async def extract_video_text(): # Douyin share link (can be the short URL or full text containing the link) share_content = """ Check out this amazing video! https://v.douyin.com/iRNBho6J/ #douyin #video """ # Call the extraction tool with optional model parameter try: text_content = await extract_douyin_text( share_link=share_content, model="paraformer-v2" # Optional: defaults to paraformer-v2 ) print(f"Extracted text: {text_content}") # Output: Complete transcription of speech in the video except ValueError as e: print(f"Configuration error: {e}") # Handle missing API key except Exception as e: print(f"Extraction failed: {e}") # Handle processing errors # Run the async function asyncio.run(extract_video_text()) ``` -------------------------------- ### Parse Douyin Video Info (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt A lightweight parser for extracting basic video metadata from a Douyin share link without downloading the content. It takes a string containing a Douyin share link and returns a JSON object with the video ID, title, download URL, and status. ```python # Direct video info parsing import json # Parse video information from share link share_link = "分享了一个抖音视频 https://v.douyin.com/iRNBho6J/" result = parse_douyin_video_info(share_link=share_link) video_data = json.loads(result) # Expected structure: # { # "video_id": "7123456789012345678", # "title": "Video Description Text", # "download_url": "https://www.iesdouyin.com/aweme/v1/play/?video_id=...", # "status": "success" # } # Error handling if video_data["status"] == "error": print(f"Failed to parse: {video_data['error']}") else: print(f"Video ID: {video_data['video_id']}") print(f"Title: {video_data['title']}") print(f"URL: {video_data['download_url']}") ``` -------------------------------- ### Safe Douyin Text Extraction with Error Handling (Python) Source: https://context7.com/yzfly/douyin-mcp-server/llms.txt This function provides a robust way to extract text from Douyin videos. It includes comprehensive error handling for API key configuration, input validation, URL parsing, and the transcription process itself. It returns a structured dictionary indicating success or failure with specific error details. ```python import json import os # Assuming DouyinProcessor class is defined elsewhere and imported # from douyin_processor import DouyinProcessor # Placeholder for DouyinProcessor for demonstration purposes class DouyinProcessor: def __init__(self, api_key): self.api_key = api_key def parse_share_url(self, share_link): if "invalid" in share_link: raise ValueError("Simulated invalid URL format") return {"url": "http://example.com/video.mp4", "video_id": "123", "title": "Sample Video"} def extract_text_from_video_url(self, video_url): if "fail" in video_url: raise Exception("Simulated transcription failure") return "This is the extracted text from the video." def safe_extract_douyin_text(share_link: str) -> dict: """ Safely extract text from Douyin video with comprehensive error handling """ result = { "success": False, "text": None, "error": None, "error_type": None } try: # Validate API key api_key = os.getenv('DASHSCOPE_API_KEY') if not api_key: result["error"] = "DASHSCOPE_API_KEY environment variable not set" result["error_type"] = "configuration" return result # Validate share link format if not share_link or not isinstance(share_link, str): result["error"] = "Invalid share link provided" result["error_type"] = "validation" return result # Initialize processor processor = DouyinProcessor(api_key=api_key) # Parse video information try: video_info = processor.parse_share_url(share_link) except ValueError as e: result["error"] = f"Invalid Douyin URL: {str(e)}" result["error_type"] = "parsing" return result # Extract text content try: text_content = processor.extract_text_from_video_url(video_info['url']) result["success"] = True result["text"] = text_content result["video_id"] = video_info["video_id"] result["title"] = video_info["title"] except Exception as e: result["error"] = f"Transcription failed: {str(e)}" result["error_type"] = "transcription" return result except Exception as e: result["error"] = f"Unexpected error: {str(e)}" result["error_type"] = "unknown" return result # Usage example: # To test the success case: # os.environ['DASHSCOPE_API_KEY'] = 'dummy_key' # result = safe_extract_douyin_text("https://v.douyin.com/iRNBho6J/") # print(f"Success Case: {result}") # To test invalid URL case: # result_invalid_url = safe_extract_douyin_text("invalid-link") # print(f"Invalid URL Case: {result_invalid_url}") # To test transcription failure case (simulated): # class DouyinProcessorFail(DouyinProcessor): # def extract_text_from_video_url(self, video_url): # raise Exception("Simulated transcription failure") # Original DouyinProcessor would need to be mocked or replaced for this test # To test configuration error case: # if 'DASHSCOPE_API_KEY' in os.environ: # del os.environ['DASHSCOPE_API_KEY'] # result_config_error = safe_extract_douyin_text("https://v.douyin.com/iRNBho6J/") # print(f"Config Error Case: {result_config_error}") ```