### Get Character Mapping Table (API) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Fetches only the character mapping table for a given font, returning a concise key-value format suitable for text decoding. Includes a Python example demonstrating how to use the API to decode JJWXC encrypted text. ```bash # 获取字符映射表 curl -X GET "http://localhost:8080/api/jjwxc_font_abcde/table" -H "Accept: application/json" # 响应示例 { "": "的", "": "是", "": "在", "": "有", "": "我" } ``` ```python import requests def decode_jjwxc_text(font_name: str, encrypted_text: str) -> str: """使用字符映射表解码晋江文学城加密文本""" response = requests.get(f"http://localhost:8080/api/{font_name}/table") if response.status_code == 200: table = response.json() decoded = "" for char in encrypted_text: decoded += table.get(char, char) return decoded raise Exception(f"获取字体失败: {response.status_code}") # 使用 decoded = decode_jjwxc_text("jjwxc_font_abcde", "加密文本内容") print(decoded) ``` -------------------------------- ### GET /html/ Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Provides an HTML page listing all cached fonts, offering a visual interface for browsing available fonts. ```APIDOC ## GET /html/ ### Description Provides an HTML page listing all cached fonts, offering a visual interface for browsing available fonts. ### Method GET ### Endpoint `/html/` ### Parameters None ### Request Example ```bash curl -X GET "http://localhost:8080/html/" ``` ### Usage Access `http://localhost:8080/html/` in your web browser. ``` -------------------------------- ### Quick Match Algorithm (Python) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Implements a fast character matching algorithm using coordinate tables (coordTable). It leverages the FontTools library to process TTF fonts and provides functions to list characters, get coordinate tables, and perform matching. Includes a utility to check glyph similarity. ```python from fontTools.ttLib import ttFont from jjwxc_font_tables.font_parser.quick import ( list_ttf_characters, get_font_coor_table, match_jjwxc_font, is_glpyh_similar ) # 加载 TTF 字体对象 ttf = ttFont.TTFont("path/to/font.ttf") # 列出字体中所有字符 characters = list_ttf_characters(ttf) print(f"字体包含 {len(characters)} 个字符") # 获取字体的完整坐标表 coor_table = get_font_coor_table(ttf) # 返回格式: {"字符": [(x1, y1), (x2, y2), ...], ...} # 执行快速匹配 table, status = match_jjwxc_font(ttf) if status == "OK": print("所有字符匹配成功") for encrypted_char, original_char in table.items(): print(f"{encrypted_char} -> {original_char}") else: print(f"以下字符需要慢速匹配: {status}") # 比较两个字符的坐标是否相似(允许 20 像素误差) coord_a = [(100, 200), (150, 250)] coord_b = [(105, 195), (148, 255)] is_similar = is_glpyh_similar(coord_a, coord_b, fuzz=20) print(f"字符相似: {is_similar}") ``` -------------------------------- ### GET /html/{font_name} Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Retrieves a detailed HTML page for a specific font, showing its information and potentially its character mappings. ```APIDOC ## GET /html/{font_name} ### Description Retrieves a detailed HTML page for a specific font, showing its information and potentially its character mappings. ### Method GET ### Endpoint `/html/{font_name}` ### Parameters #### Path Parameters - **font_name** (string) - Required - The name of the font for which to display the detail page (e.g., `jjwxc_font_abcde`). ### Request Example ```bash curl -X GET "http://localhost:8080/html/jjwxc_font_abcde" ``` ### Usage Access `http://localhost:8080/html/jjwxc_font_abcde` in your web browser. ``` -------------------------------- ### GET /api/jjwxc_font_abcde/bytes Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Downloads the raw font file in WOFF2 format, providing the binary data for local rendering or further analysis. ```APIDOC ## GET /api/jjwxc_font_abcde/bytes ### Description Downloads the raw font file in WOFF2 format, providing the binary data for local rendering or further analysis. ### Method GET ### Endpoint `/api/jjwxc_font_abcde/bytes` ### Parameters #### Path Parameters - **font_name** (string) - Required - The name of the font file to download (e.g., `jjwxc_font_abcde`). Must follow the format `jjwxcfont_xxxxx`. ### Request Example ```bash curl -X GET "http://localhost:8080/api/jjwxc_font_abcde/bytes" -H "Accept: application/font-woff2" -o "jjwxc_font_abcde.woff" ``` ### Response #### Success Response (200) - **(binary)** - The WOFF2 font file content. #### Response Headers Example ``` Content-Type: application/font-woff2 Content-Disposition: attachment; filename="jjwxc_font_abcde.woff" ETag: "a1b2c3d4..." Cache-Control: max-age=2678400 ``` #### Error Responses - **404** - Font not found. ``` -------------------------------- ### Get Font Full Information (API) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Retrieves complete parsing information for a specified font name, including name, hash, and character mapping table. Returns JSON data and supports CORS. Handles invalid font name formats (403) and font not found (404) errors. ```bash # 获取字体完整信息(不包含字节数据) curl -X GET "http://localhost:8080/api/jjwxc_font_abcde" -H "Accept: application/json" # 响应示例 { "name": "jjwxc_font_abcde", "hashsum": "a1b2c3d4e5f6789...", "table": { "": "的", "": "是", "": "在" } } # 错误响应 # 403 - 字体名称格式无效(必须为 jjwxcfont_xxxxx 格式) # 404 - 字体不存在 # 503 - 服务暂时不可用 ``` -------------------------------- ### Slow Match Tool - Jinjiang Font (curl) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Demonstrates how to use the slow match tool via curl to parse Jinjiang Literature City fonts through a web interface. It shows the GET request for the tool's homepage and a POST request for performing the slow match with specified parameters. ```bash # 访问工具首页 curl -X GET "http://localhost:8080/tools/" # POST 请求进行慢速匹配 curl -X POST "http://localhost:8080/tools/slow-match/jjwxc" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "jjwxc_font_name=jjwxcfont_abcde&std_font=SourceHanSansSC-Normal&guest_range=jjwxc" # 参数说明: # - jjwxc_font_name: 字体名称(必须符合 jjwxcfont_xxxxx 格式) # - std_font: 标准字体(SourceHanSansSC-Normal 或 SourceHanSansSC-Regular) # - guest_range: 猜测范围(jjwxc 或 2500 常用字) ``` -------------------------------- ### GET /healthcheck Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt A health check endpoint used for container orchestration and load balancers to verify the service's operational status. ```APIDOC ## GET /healthcheck ### Description A health check endpoint used for container orchestration and load balancers to verify the service's operational status. ### Method GET ### Endpoint `/healthcheck` ### Parameters None ### Request Example ```bash curl -X GET "http://localhost:8080/healthcheck" ``` ### Response #### Success Response (200) - **Body**: `OK` ### Docker Healthcheck Configuration Example ```dockerfile HEALTHCHECK --interval=5m CMD curl -sf http://127.0.0.1:8080/healthcheck || exit 1 ``` ``` -------------------------------- ### GET /api/jjwxc_font_abcde/table Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Retrieves only the character mapping table for a specified font, in a concise key-value format suitable for text decoding. ```APIDOC ## GET /api/jjwxc_font_abcde/table ### Description Retrieves only the character mapping table for a specified font, in a concise key-value format suitable for text decoding. ### Method GET ### Endpoint `/api/jjwxc_font_abcde/table` ### Parameters #### Path Parameters - **font_name** (string) - Required - The name of the font whose table is to be retrieved (e.g., `jjwxc_font_abcde`). Must follow the format `jjwxcfont_xxxxx`. ### Request Example ```bash curl -X GET "http://localhost:8080/api/jjwxc_font_abcde/table" -H "Accept: application/json" ``` ### Request Example (Python) ```python import requests def decode_jjwxc_text(font_name: str, encrypted_text: str) -> str: """Use character mapping table to decode Jinjiang Literature City encrypted text""" response = requests.get(f"http://localhost:8080/{font_name}/table") if response.status_code == 200: table = response.json() decoded = "" for char in encrypted_text: decoded += table.get(char, char) return decoded raise Exception(f"Failed to get font: {response.status_code}") # Usage decoded = decode_jjwxc_text("jjwxc_font_abcde", "encrypted text content") print(decoded) ``` ### Response #### Success Response (200) - **(object)** - A key-value map where keys are encrypted characters and values are their corresponding original characters. #### Response Example ```json { "": "的", "": "是", "": "在", "": "有", "": "我" } ``` #### Error Responses - **404** - Font not found. ``` -------------------------------- ### Health Check Endpoint (API) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt A health check endpoint designed for container orchestration and load balancers. It returns a simple 'OK' response with an HTTP 200 status. Includes an example Docker HEALTHCHECK configuration. ```bash # 健康检查 curl -X GET "http://localhost:8080/healthcheck" # 响应 # HTTP 200 OK # Body: OK # Docker 健康检查配置 HEALTHCHECK --interval=5m CMD curl -sf http://127.0.0.1:8080/healthcheck || exit 1 ``` -------------------------------- ### GET /api/jjwxc_font_abcde Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Retrieves complete information for a specified font, including its name, hash, and character mapping table. Supports CORS and caching. ```APIDOC ## GET /api/jjwxc_font_abcde ### Description Retrieves complete information for a specified font, including its name, hash, and character mapping table. Supports CORS and caching. ### Method GET ### Endpoint `/api/jjwxc_font_abcde` ### Parameters #### Path Parameters - **font_name** (string) - Required - The name of the font to retrieve (e.g., `jjwxc_font_abcde`). Must follow the format `jjwxcfont_xxxxx`. ### Request Example ```bash curl -X GET "http://localhost:8080/api/jjwxc_font_abcde" -H "Accept: application/json" ``` ### Response #### Success Response (200) - **name** (string) - The name of the font. - **hashsum** (string) - The hashsum of the font file. - **table** (object) - A key-value map where keys are encrypted characters and values are their corresponding original characters. #### Response Example ```json { "name": "jjwxc_font_abcde", "hashsum": "a1b2c3d4e5f6789...", "table": { "": "的", "": "是", "": "在" } } ``` #### Error Responses - **403** - Invalid font name format (must be `jjwxcfont_xxxxx`). - **404** - Font not found. - **503** - Service temporarily unavailable. ``` -------------------------------- ### Manual Docker Build Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Instructions for manually building the Docker image and running the container. ```APIDOC ## Manual Docker Build Instructions for manually building the Docker image and running the container. ### Description This section provides steps for building the Docker image from source and running it as a container. ### Method Standard Docker commands (`docker build`, `docker run`) are used. ### Endpoints This section describes deployment steps, not API endpoints. ### Parameters - `docker build -t jjwxc_font_tables .`: Builds the Docker image. - `docker run`: Runs the Docker container. - `--name jjwxc_font_tables`: Assigns a name to the container. - `-p 8080:8080`: Maps host port 8080 to container port 8080. - `-v jjwxc_data:/app/instance`: Mounts a volume for data persistence. - `-e ENABLE_TOOLS=true`: Sets an environment variable to enable tools. - `docker exec jjwxc_font_tables flask init-db`: Command to initialize the database inside the running container. ### Request Example (Docker Commands) ```bash # Build the image docker build -t jjwxc_font_tables . # Run the container docker run -d \ --name jjwxc_font_tables \ -p 8080:8080 \ -v jjwxc_data:/app/instance \ -e ENABLE_TOOLS=true \ jjwxc_font_tables # Initialize the database (optional) docker exec jjwxc_font_tables flask init-db ``` ### Response - **Success Response**: The Docker image is built, and the container is running. - **Error Response**: Docker commands may output errors if the build or run process fails. ``` -------------------------------- ### Manual Docker Build and Run Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Instructions for manually building the Docker image and running the JJWXC Font Tables container. This includes commands for building the image, running the container with port mapping and volume mounting, and optionally initializing the database. ```bash # 构建镜像 docker build -t jjwxc_font_tables . # 运行容器 docker run -d \ --name jjwxc_font_tables \ -p 8080:8080 \ -v jjwxc_data:/app/instance \ -e ENABLE_TOOLS=true \ jjwxc_font_tables # 初始化数据库(可选) docker exec jjwxc_font_tables flask init-db ``` -------------------------------- ### Docker Compose Commands Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Command-line instructions for managing the JJWXC Font Tables service using Docker Compose. This includes building the image, starting/stopping the service, viewing logs, and cleaning up data volumes. ```bash # 构建并启动服务 docker-compose up -d --build # 查看日志 docker-compose logs -f jjwxc_font_tables # 停止服务 docker-compose down # 清理数据卷 docker-compose down -v ``` -------------------------------- ### Jinja2 模板渲染字体列表 Source: https://github.com/404-novel-project/jjwxc_font_tables/blob/dev/jjwxc_font_tables/templates/list.html 此 Jinja2 模板用于生成自定义字体列表。它遍历 `font_name_list` 并为每种字体创建一个 Markdown 格式的链接,指向 `html.get_font` 路由。模板继承自 `base.html` 并定义了 `title`, `head`, 和 `main` 块的内容。 ```jinja2 {% extends 'base.html' %} {% block title %}晋江文学城自定义字体对照表{% endblock %} {% block head %} .section { margin-top: 1.5em; display: grid; grid-template-columns: 30% 30% 30%; } {% endblock %} {% block main %} 晋江文学城自定义字体对照表 ============= {%- for font_name in font_name_list -%} [{{ font_name }}({{ url_for('html.get_font', font_name=font_name) }}) {%- endfor -%} {% endblock %} ``` -------------------------------- ### Docker Compose Deployment Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Provides a complete containerized deployment solution using Docker Compose, including data persistence configuration. ```APIDOC ## Docker Compose Deployment Provides a complete containerized deployment solution using Docker Compose, including data persistence configuration. ### Description This section outlines how to deploy the JJWXC Font Tables application using Docker Compose. ### Method Docker Compose commands are used to build, run, and manage the application containers. ### Endpoints This section describes deployment steps, not API endpoints. ### Parameters - `docker-compose.yaml` (Configuration file): - `services.jjwxc_font_tables.image`: The Docker image name. - `services.jjwxc_font_tables.restart`: Restart policy. - `services.jjwxc_font_tables.build.context`: Build context path. - `services.jjwxc_font_tables.ports`: Port mapping. - `services.jjwxc_font_tables.volumes`: Volume for data persistence. - `services.jjwxc_font_tables.environment.ENABLE_TOOLS`: Environment variable to enable advanced tools. - `volumes.jjwxc_font_tables-data`: Named volume for data persistence. ### Request Example (Docker Compose Commands) ```yaml # docker-compose.yaml version: "3" services: jjwxc_font_tables: image: jjwxc_font_tables restart: always build: context: . ports: - "8080:8080" volumes: - jjwxc_font_tables-data:/app/instance environment: - ENABLE_TOOLS=true # Enable advanced tools functionality volumes: jjwxc_font_tables-data: ``` ```bash # Build and start the service docker-compose up -d --build # View logs docker-compose logs -f jjwxc_font_tables # Stop the service docker-compose down # Clean up data volumes docker-compose down -v ``` ### Response - **Success Response**: The application is deployed and running in Docker containers. - **Error Response**: Docker Compose commands may output errors if configuration or execution fails. ``` -------------------------------- ### Download Font File (API) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Provides the raw font file in WOFF2 format as binary data. This can be used for local rendering or further analysis. The response includes typical headers like Content-Type and Content-Disposition. ```bash # 下载字体文件 curl -X GET "http://localhost:8080/api/jjwxc_font_abcde/bytes" -H "Accept: application/font-woff2" -o "jjwxc_font_abcde.woff" # 响应头示例 # Content-Type: application/font-woff2 # Content-Disposition: attachment; filename="jjwxc_font_abcde.woff" # ETag: "a1b2c3d4..." # Cache-Control: max-age=2678400 ``` -------------------------------- ### Docker Compose Deployment for JJWXC Font Tables Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Provides a complete containerized deployment solution using Docker Compose, including data persistence configuration. It outlines the service definition, ports, volumes, and environment variables for running the application. ```yaml # docker-compose.yaml version: "3" services: jjwxc_font_tables: image: jjwxc_font_tables restart: always build: context: . ports: - "8080:8080" volumes: - jjwxc_font_tables-data:/app/instance environment: - ENABLE_TOOLS=true # 启用高级工具功能 volumes: jjwxc_font_tables-data: ``` -------------------------------- ### Database Model and Operations with SQLAlchemy and Flask Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Manages the persistence of font data using SQLAlchemy ORM within a Flask application. It demonstrates initializing the database, creating font records, and querying them. ```python from flask import Flask from jjwxc_font_tables.db import db, Font, init_db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///jjwxc.sqlite' db.init_app(app) with app.app_context(): # 初始化数据库(清空并重建) init_db() # 创建字体记录 font = Font( name="jjwxcfont_abcde", bytes=b"font binary data...", hashsum="a1b2c3d4e5f6...", table={"": "的", "": "是"} # 自动排序并 JSON 序列化 ) db.session.add(font) db.session.commit() # 查询字体 import sqlalchemy as sa result = db.session.execute( sa.select(Font).where(Font.name.is_("jjwxcfont_abcde")) ).scalar_one() # 转换为字典 font_dict = result.to_dict() print(font_dict) # {'name': 'jjwxcfont_abcde', 'bytes': b'...', 'hashsum': '...', 'table': {...}} ``` -------------------------------- ### Slow Match Tool - Upload Font (curl) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Shows how to use the slow match tool to parse custom uploaded font files using curl. This command demonstrates uploading a font file (e.g., .woff2) along with standard font and guess range parameters. ```bash # 上传字体文件进行解析 curl -X POST "http://localhost:8080/tools/slow-match/upload" \ -F "upload_font=@custom_font.woff2" \ -F "std_font=SourceHanSansSC-Normal" \ -F "guest_range=2500" # 支持的字体格式:TTF、OTF、WOFF、WOFF2 ``` -------------------------------- ### Download and Parse Fonts with Python Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Downloads font files from Jinjiang Literature City servers and parses them into TTFont objects using Python. It handles WOFF2 to TTF conversion and provides a convenient function to retrieve font information including name and hash. ```python import asyncio from jjwxc_font_tables.font_parser.download import ( request_font, woff2_to_ttf, get_font ) async def download_example(): # 下载字体二进制数据 font_bytes, status = await request_font("jjwxcfont_abcde", retry=5) if status == "OK": print(f"下载成功,大小: {len(font_bytes)} bytes") # 将 WOFF2 转换为 TTFont 对象 ttf = woff2_to_ttf(font_bytes) print(f"字体版本: {ttf['name'].getDebugName(5)}") elif status == "404": print("字体不存在") else: print("下载失败") # 使用封装函数获取完整字体信息 font = await get_font("jjwxcfont_abcde") if font.get("status") == "OK": print(f"字体名称: {font['name']}") print(f"SHA1 哈希: {font['hashsum']}") # font['ttf'] 是 TTFont 对象 # font['bytes'] 是原始二进制数据 asyncio.run(download_example()) ``` -------------------------------- ### Tool Page - Upload Font Slow Match Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Supports uploading custom font files for parsing using the slow matching tool. Requires ENABLE_TOOLS to be true. ```APIDOC ## Tool Page - Upload Font Slow Match Supports uploading custom font files for parsing using the slow matching tool. Requires `ENABLE_TOOLS` to be true. ### Description This tool allows users to upload their own font files for analysis. ### Method HTTP POST request with multipart/form-data is used for uploading files. ### Endpoint - `POST /tools/slow-match/upload`: Upload a font file for slow matching. ### Parameters #### Request Body (Form Data) - **upload_font** (file) - Required - The font file to upload (supported formats: TTF, OTF, WOFF, WOFF2). - **std_font** (string) - Required - The standard font to compare against (e.g., "SourceHanSansSC-Normal"). - **guest_range** (string) - Required - The guessed character range (e.g., "2500 common characters"). ### Request Example ```bash # Upload a font file for parsing curl -X POST "http://localhost:8080/tools/slow-match/upload" \ -F "upload_font=@custom_font.woff2" \ -F "std_font=SourceHanSansSC-Normal" \ -F "guest_range=2500" ``` ### Response - **Success Response**: The uploaded font is processed, and results are returned. - **Error Response**: Errors may occur if the file is invalid, unsupported, or parameters are missing. ``` -------------------------------- ### Font Downloading and Parsing Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt This section details how to download font files from Jinjiang Literature City servers and parse them into TTFont objects using Python. ```APIDOC ## Font Downloading and Parsing This section details how to download font files from Jinjiang Literature City servers and parse them into TTFont objects using Python. ### Method Asynchronous Python functions are used for downloading and parsing. ### Endpoints No direct HTTP endpoints are exposed for this functionality; it's handled via Python library calls. ### Parameters - `request_font(font_name: str, retry: int)`: Downloads font binary data. - `font_name` (str): The name of the font to download (e.g., "jjwxcfont_abcde"). - `retry` (int): Number of retries for the download request. - `woff2_to_ttf(font_bytes: bytes)`: Converts WOFF2 font data to a TTFont object. - `font_bytes` (bytes): The binary content of the WOFF2 font file. - `get_font(font_name: str)`: Retrieves complete font information, including the TTFont object and raw binary data. - `font_name` (str): The name of the font. ### Request Example ```python import asyncio from jjwxc_font_tables.font_parser.download import ( request_font, woff2_to_ttf, get_font ) async def download_example(): # Download font binary data font_bytes, status = await request_font("jjwxcfont_abcde", retry=5) if status == "OK": print(f"Download successful, size: {len(font_bytes)} bytes") # Convert WOFF2 to TTFont object ttf = woff2_to_ttf(font_bytes) print(f"Font version: {ttf['name'].getDebugName(5)}") elif status == "404": print("Font not found") else: print("Download failed") # Use the encapsulated function to get full font information font = await get_font("jjwxcfont_abcde") if font.get("status") == "OK": print(f"Font name: {font['name']}") print(f"SHA1 hash: {font['hashsum']}") # font['ttf'] is the TTFont object # font['bytes'] is the original binary data asyncio.run(download_example()) ``` ### Response - **Success Response**: Returns font data or TTFont object. - **Error Response**: Indicates download failure or font not found. ``` -------------------------------- ### Slow Match Algorithm (Image Recognition) (Python) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Implements a fallback character matching algorithm using image recognition for cases where the quick match fails. It renders characters to images and calculates overlap using Pillow and NumPy. This method is slower but more robust. It requires a standard font for rendering and a list of potential characters to guess from. ```python import io from PIL import ImageFont from jjwxc_font_tables.font_parser.slow import ( draw, compare_im_np, match_font, match_jjwxc_font, load_SourceHanSansSC_Normal ) import numpy as np # 绘制字符图像(96px 字号,白底黑字) std_font = load_SourceHanSansSC_Normal() char_image = draw("中", std_font) char_image.save("char_image.png") # 比较两个字符图像的相似度 test_array = np.asarray(draw("测", std_font)) std_array = np.asarray(draw("测", std_font)) similarity = compare_im_np(test_array, std_array) print(f"相似度: {similarity:.2%}") # 相似度: 100.00% # 使用慢速匹配解析字体 with open("font.woff2", "rb") as font_fd: from fontTools.ttLib import ttFont ttf = ttFont.TTFont(font_fd) font_fd.seek(0) # 定义猜测范围(常用汉字列表) guest_range = ["的", "是", "在", "有", "我", "他", "这", "为"] table = match_jjwxc_font( jjwxc_font_fd=font_fd, jjwxc_font_ttf=ttf, std_font=std_font, guest_range=guest_range ) print(table) ``` -------------------------------- ### HTML Font List Page (API) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Accesses a web page listing all cached fonts, offering a visual browsing interface. Also shows how to access the detail page for a specific font. ```bash # 访问字体列表页面 curl -X GET "http://localhost:8080/html/" # 或直接在浏览器访问 # http://localhost:8080/html/ # 访问特定字体的详情页面 curl -X GET "http://localhost:8080/html/jjwxc_font_abcde" ``` -------------------------------- ### Tool Page - Jinjiang Font Slow Match Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Access the slow matching tool via a web interface to parse Jinjiang Literature City fonts using a slow matching algorithm. Requires ENABLE_TOOLS to be true. ```APIDOC ## Tool Page - Jinjiang Font Slow Match Access the slow matching tool via a web interface to parse Jinjiang Literature City fonts using a slow matching algorithm. Requires `ENABLE_TOOLS` to be true. ### Description This tool provides a web interface for performing slow matching on Jinjiang Literature City fonts. ### Method HTTP GET and POST requests are used to interact with the tool. ### Endpoint - `GET /tools/`: Access the tool's homepage. - `POST /tools/slow-match/jjwxc`: Perform slow matching using a Jinjiang font. ### Parameters #### Query Parameters (for POST /tools/slow-match/jjwxc) - **jjwxc_font_name** (string) - Required - The name of the Jinjiang font (e.g., "jjwxcfont_abcde"). - **std_font** (string) - Required - The standard font to compare against (e.g., "SourceHanSansSC-Normal"). - **guest_range** (string) - Required - The guessed character range (e.g., "jjwxc" or "2500 common characters"). ### Request Example ```bash # Access the tool homepage curl -X GET "http://localhost:8080/tools/" # POST request for slow matching curl -X POST "http://localhost:8080/tools/slow-match/jjwxc" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "jjwxc_font_name=jjwxcfont_abcde&std_font=SourceHanSansSC-Normal&guest_range=jjwxc" ``` ### Response - **Success Response**: The tool processes the request and returns matching results or information. - **Error Response**: Errors may occur if parameters are missing or invalid. ``` -------------------------------- ### Database Model and Operations Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt This section describes the database models and operations for persisting font data using SQLAlchemy ORM. ```APIDOC ## Database Model and Operations This section describes the database models and operations for persisting font data using SQLAlchemy ORM. ### Description Font data is stored persistently using SQLAlchemy ORM to manage font records. ### Method Database operations are performed using SQLAlchemy within a Flask application context. ### Endpoints No direct HTTP endpoints are exposed for database operations; they are handled via Python library calls. ### Parameters - `Font` (Model): SQLAlchemy model for font records. - `name` (str): The name of the font. - `bytes` (bytes): The binary data of the font. - `hashsum` (str): The hash sum of the font. - `table` (dict): A dictionary representing the font's character mapping table. - `init_db()`: Initializes the database (clears and recreates). - `db.session.add(font)`: Adds a font record to the session. - `db.session.commit()`: Commits the transaction. - `db.session.execute(sa.select(Font).where(Font.name.is_(...)))`: Executes a query to select font records. ### Request Example ```python from flask import Flask from jjwxc_font_tables.db import db, Font, init_db import sqlalchemy as sa app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///jjwxc.sqlite' db.init_app(app) with app.app_context(): # Initialize the database (clear and recreate) init_db() # Create a font record font = Font( name="jjwxcfont_abcde", bytes=b"font binary data...", hashsum="a1b2c3d4e5f6...", table={" ": "的", " ": "是"} # Automatically sorted and JSON serialized ) db.session.add(font) db.session.commit() # Query for the font result = db.session.execute( sa.select(Font).where(Font.name.is_("jjwxcfont_abcde")) ).scalar_one() # Convert to dictionary font_dict = result.to_dict() print(font_dict) # {'name': 'jjwxcfont_abcde', 'bytes': b'...', 'hashsum': '...', 'table': {...}} ``` ### Response - **Success Response**: Font records are created, updated, or queried from the database. - **Response Example**: A dictionary representation of a font record is printed. ``` -------------------------------- ### Coordinate Table Utility Functions in Python Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Provides utility functions for loading, merging, and deduplicating font coordinate tables. It includes functions for loading standard tables with caching, checking coordinate matches, and performing merge and deduplication operations. ```python from jjwxc_font_tables.lib import ( load_jjwxc_std_font_coord_table, merge_coor_table, deduplicate_coor_table, is_coor_match ) # 加载标准坐标表(带 LRU 缓存) std_coor_table = load_jjwxc_std_font_coord_table() # 返回格式: [("字符", [(x1, y1), (x2, y2), ...]), ...] # 比较两个坐标是否完全匹配 coord_a = [(100, 200), (150, 250)] coord_b = [(100, 200), (150, 250)] print(is_coor_match(coord_a, coord_b)) # True # 合并两个坐标表 source = [("的", [(1, 2)]), ("是", [(3, 4)])] target = [("在", [(5, 6)])] merged = merge_coor_table(source, target) # 结果: [("在", [...]), ("的", [...]), ("是", [...])] # 去除重复项 duplicated = [("的", [(1, 2)]), ("的", [(1, 2)]), ("是", [(3, 4)])] unique = deduplicate_coor_table(duplicated) print(len(unique)) # 2 ``` -------------------------------- ### HTML Template for Custom Font Upload and Display Source: https://github.com/404-novel-project/jjwxc_font_tables/blob/dev/jjwxc_font_tables/templates/tools/slow_match_upload_font.html This Jinja2 HTML template defines the structure for uploading and displaying custom fonts. It includes CSS rules for font family and @font-face declarations to load the font from a URL. The template also iterates through character mappings, displaying their hexadecimal codes and rendered forms. ```html {% extends 'base.html' %} {% block title %}上传自定义字体:{{ font.name }}{% endblock %} {% block head %} .upload-font { font-family: {{ font.name.replace('.','\_') }}, 'Microsoft YaHei', PingFangSC-Regular, HelveticaNeue-Light, 'Helvetica Neue Light', sans-serif !important;; } @font-face { font-family: {{ font.name.replace('.','\_') }}; src: url('{{ url_for('tools.get_slow_match_upload_font', filename=font_url_filename) }}') format('{{ font_url_format }}'); } {% endblock %} {% block main %} 上传自定义字体:{{ font.name }} ======================= {%- for item in font.table.items() -%} {%- endfor -%} 自定义字符(编码) 自定义字符(渲染) 通用字符 {{ get_charater_hex(item[0]) }} {{ item[0] }} {{ item[1] }} {% endblock %} ``` -------------------------------- ### Coordinate Table Utility Functions Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Provides utility functions for loading, merging, and deduplicating font coordinate tables. ```APIDOC ## Coordinate Table Utility Functions Provides utility functions for loading, merging, and deduplicating font coordinate tables. ### Description These functions assist in managing character coordinate data derived from font files. ### Method These are standalone Python functions. ### Endpoints No direct HTTP endpoints are exposed for these utility functions. ### Parameters - `load_jjwxc_std_font_coord_table()`: Loads the standard coordinate table with LRU caching. - `merge_coor_table(source: list, target: list)`: Merges two coordinate tables. - `source` (list): The source coordinate table. - `target` (list): The target coordinate table. - `deduplicate_coor_table(coor_table: list)`: Removes duplicate entries from a coordinate table. - `coor_table` (list): The coordinate table to deduplicate. - `is_coor_match(coord_a: list, coord_b: list)`: Checks if two coordinate lists are identical. - `coord_a` (list): The first coordinate list. - `coord_b` (list): The second coordinate list. ### Request Example ```python from jjwxc_font_tables.lib import ( load_jjwxc_std_font_coord_table, merge_coor_table, deduplicate_coor_table, is_coor_match ) # Load the standard coordinate table (with LRU cache) std_coor_table = load_jjwxc_std_font_coord_table() # Format: [("character", [(x1, y1), (x2, y2), ...]), ...] # Compare two coordinates for exact match coord_a = [(100, 200), (150, 250)] coord_b = [(100, 200), (150, 250)] print(is_coor_match(coord_a, coord_b)) # True # Merge two coordinate tables source = [("的", [(1, 2)]), ("是", [(3, 4)])] target = [("在", [(5, 6)])] merged = merge_coor_table(source, target) # Result: [("在", [...]), ("的", [...]), ("是", [...])] # Deduplicate entries duplicated = [("的", [(1, 2)]), ("的", [(1, 2)]), ("是", [(3, 4)])] unique = deduplicate_coor_table(duplicated) print(len(unique)) # 2 ``` ### Response - **Success Response**: Returns processed coordinate tables or boolean match results. ``` -------------------------------- ### Jinja Template for JJWXC Font Tables Source: https://github.com/404-novel-project/jjwxc_font_tables/blob/dev/jjwxc_font_tables/templates/font.html This Jinja template defines the structure for displaying font information, including CSS for font family and font face, and tables for character encoding and rendering. It iterates through font data to populate the tables. ```html {% extends 'base.html' %} {% block title %}{{ font.name }}{% endblock %} {% block head %} .jjfont { font-family: {{ font.name }}, 'Microsoft YaHei', PingFangSC-Regular, HelveticaNeue-Light, 'Helvetica Neue Light', sans-serif !important;; } @font-face { font-family: {{ font.name }}; src: url('https://static.jjwxc.net/tmp/fonts/{{ font.name }}.woff2?h=my.jjwxc.net') format('woff2'); } {% endblock %} {% block main %} {{ font.name }} =============== {% for item in font.table.items() %} {% endfor %} 晋江字符(编码) 晋江字符(渲染) 通用字符 {{ get_charater_hex(item[0]) }} {{ item[0] }} {{ item[1] }} {% endblock %} ``` -------------------------------- ### Font Name Validator (Python) Source: https://context7.com/404-novel-project/jjwxc_font_tables/llms.txt Validates if a font name adheres to the JJWXC naming convention, which requires the prefix 'jjwxcfont_' followed by a 5-character alphanumeric string. Demonstrates usage with both valid and invalid names. ```python from jjwxc_font_tables.font_parser import validator # 验证字体名称格式 valid_name = "jjwxcfont_abcde" invalid_name = "some_font" print(validator(valid_name)) # True print(validator(invalid_name)) # False # 验证规则: # 1. 总长度必须为 15 个字符 # 2. 必须以 "jjwxcfont_" 开头 # 3. 后缀为 5 位字母数字组合 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.