Skip to content

dongzhigang13305312738-art/paper-skills / complete-example

complete-example

Verified

当用户明确要求"填充示例内容""生成示例""补充 LaTeX 示例"时使用。AI 增强版 LaTeX 示例智能生成器,实现 AI 与硬编码的有机融合:AI 做"语义理解"(分析章节主题、推理资源相关性、生成连贯叙述),硬编码做"结构保护"(格式验证、哈希校验、访问控制)。

scripts/semantic_analyzer.py

View on GitHub
"""
SemanticAnalyzer - AI 驱动语义分析器
🧠 AI:理解章节主题、推理资源相关性、评估内容质量
"""

from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from pathlib import Path
import json


@dataclass
class SectionTheme:
    """章节主题分析结果"""
    theme: str                      # 章节核心主题
    key_concepts: List[str]         # 关键概念列表
    writing_style: str              # 写作风格:学术/技术/说明
    suggested_resources: List[str]  # 建议的资源类型
    tone: str                       # 语调:正式/通俗
    target_audience: str            # 目标读者:专家/评审/大众


@dataclass
class ResourceRelevance:
    """资源相关性评估结果"""
    resource_path: str
    relevance_score: float          # 0-1 相关性分数
    reason: str                     # AI 给出的理由
    suggested_usage: str            # 建议的使用方式


class SemanticAnalyzer:
    """AI 驱动的语义分析器"""

    def __init__(self, llm_client, prompts: Optional[Dict[str, str]] = None):
        """
        Args:
            llm_client: LLM 客户端(Claude/OpenAI/本地模型)
            prompts: 来自 config.yaml 的 prompts(可选,用于集中化管理)
        """
        self.llm = llm_client
        self.prompts = prompts or {}

    def _safe_json(self, text: str) -> Dict[str, Any]:
        """尽量从 LLM 输出中解析 JSON;失败则返回空 dict。"""
        try:
            return json.loads(text)
        except Exception:
            # 兼容 LLM 返回包含说明文字的情况:截取第一个 JSON 对象
            try:
                start = text.find("{")
                end = text.rfind("}")
                if start != -1 and end != -1 and end > start:
                    return json.loads(text[start:end + 1])
            except Exception:
                pass
        return {}

    def analyze_section_theme(self, tex_content: str) -> SectionTheme:
        """
        分析章节的核心主题和写作意图

        Args:
            tex_content: LaTeX 文件内容(前 2000 字符)

        Returns:
            SectionTheme: 结构化的主题分析结果
        """
        tmpl = self.prompts.get("analyze_theme")
        if tmpl:
            prompt = tmpl.format(max_chars=2000, content=tex_content[:2000])
        else:
            prompt = f"""
你是一位专业的学术写作分析专家。请分析以下 LaTeX 章节的内容主题。

章节内容(前 2000 字符):
{tex_content[:2000]}

请返回 JSON 格式的分析结果:
{{
  "theme": "章节的核心主题(一句话概括)",
  "key_concepts": ["关键概念1", "关键概念2", "关键概念3"],
  "writing_style": "学术/技术/说明/混合",
  "suggested_resources": ["建议的图片类型", "建议的文献领域"],
  "tone": "正式/半正式/通俗",
  "target_audience": "评审专家/同行/学生/大众"
}}
"""

        response = self.llm.complete(prompt, response_format="json", temperature=0.3)
        data = self._safe_json(response)

        # Robust defaults for mock/partial outputs.
        return SectionTheme(
            theme=str(data.get("theme") or "章节主题(未识别)"),
            key_concepts=list(data.get("key_concepts") or ["关键概念A", "关键概念B", "关键概念C"]),
            writing_style=str(data.get("writing_style") or "学术"),
            suggested_resources=list(data.get("suggested_resources") or ["示意图", "相关文献"]),
            tone=str(data.get("tone") or "正式"),
            target_audience=str(data.get("target_audience") or "评审专家"),
        )

    def reason_resource_relevance(
        self,
        resource_info: 'ResourceInfo',
        section_theme: SectionTheme
    ) -> ResourceRelevance:
        """
        推理资源与章节的相关性

        Args:
            resource_info: 资源信息(图片/代码/文献)
            section_theme: 章节主题

        Returns:
            ResourceRelevance: 相关性评估结果
        """
        tmpl = self.prompts.get("reason_relevance")
        if tmpl:
            prompt = tmpl.format(
                section_theme=section_theme.theme,
                key_concepts=", ".join(section_theme.key_concepts),
                writing_style=section_theme.writing_style,
                resource_path=resource_info.path,
                resource_type=resource_info.type,
                metadata=resource_info.metadata,
            )
        else:
            prompt = f"""
你是一位专业的学术写作顾问。请评估以下资源是否适合用于指定章节。

章节信息:
- 主题:{section_theme.theme}
- 关键概念:{', '.join(section_theme.key_concepts)}
- 写作风格:{section_theme.writing_style}
- 建议资源:{', '.join(section_theme.suggested_resources)}

资源信息:
- 路径:{resource_info.path}
- 类型:{resource_info.type}
- 元数据:{resource_info.metadata}

请返回 JSON 格式的评估结果:
{{
  "relevance_score": 0.85,
  "reason": "详细说明理由(100-200字)",
  "suggested_usage": "建议如何使用这个资源"
}}
"""

        response = self.llm.complete(prompt, response_format="json", temperature=0.3)
        data = self._safe_json(response)

        score = data.get("relevance_score")
        try:
            score = float(score)
        except Exception:
            score = 0.5

        return ResourceRelevance(
            resource_path=resource_info.path,
            relevance_score=max(0.0, min(1.0, score)),
            reason=str(data.get("reason") or "(未提供理由)"),
            suggested_usage=str(data.get("suggested_usage") or "(未提供建议用法)"),
        )

    def generate_contextual_description(
        self,
        resource: 'ResourceInfo',
        context: str,
        usage_hint: str = None
    ) -> str:
        """
        为资源生成符合上下文的描述文字

        Args:
            resource: 资源信息
            context: 上下文内容(章节片段)
            usage_hint: 使用提示(可选)

        Returns:
            str: 自然的描述文字(50-100 字)
        """
        prompt = f"""
你是一位经验丰富的学术写作者。请为以下资源生成一段自然的描述文字。

上下文(章节片段):
{context[:500]}

资源信息:
- 文件名:{resource.filename}
- 类型:{resource.type}
- 建议用途:{usage_hint or '未指定'}

要求:
1. 生成 50-100 字的描述文字
2. 符合学术写作风格
3. 与上下文自然衔接
4. 包含适当的引入语(如"如图 X 所示"、"根据文献 X"等)

只返回描述文字,不要解释。
"""

        return self.llm.complete(prompt, temperature=0.7)

    def evaluate_content_quality(
        self,
        content: str,
        section_theme: SectionTheme = None
    ) -> Dict[str, Any]:
        """
        评估生成内容的质量

        Args:
            content: 生成的内容
            section_theme: 章节主题(可选,用于对比)

        Returns:
            Dict: 质量评估报告
        """
        prompt = f"""
你是一位严谨的学术写作评审专家。请评估以下示例内容的质量。

评估内容:
{content[:2000]}

章节主题(供参考):
{section_theme.theme if section_theme else '未指定'}

请返回 JSON 格式的评估报告:
{{
  "coherence": 0.92,  // 连贯性评分 0-1
  "academic_tone": 0.88,  // 学术风格评分 0-1
  "resource_integration": "自然/生硬/无",  // 资源整合评价
  "strengths": ["优点1", "优点2"],
  "weaknesses": ["不足1", "不足2"],
  "suggestions": ["改进建议1", "改进建议2"],
  "overall_score": 0.90  // 总体评分 0-1
}}
"""

        response = self.llm.complete(prompt, response_format="json", temperature=0.3)
        data = self._safe_json(response)
        # Provide defaults so the pipeline can continue under MockLLMClient.
        return {
            "coherence": float(data.get("coherence") or 0.0),
            "academic_tone": float(data.get("academic_tone") or 0.0),
            "resource_integration": data.get("resource_integration") or "无",
            "strengths": data.get("strengths") or [],
            "weaknesses": data.get("weaknesses") or [],
            "suggestions": data.get("suggestions") or [],
            "overall_score": float(data.get("overall_score") or 0.0),
        }
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall