You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from fastapi import APIRouter
from typing import List
from fastapi import APIRouter, HTTPException
from app.schemas.user import ChapterRelationCreate, ChapterRelationResponse
from app.services.user_service import create_chapter_relation, get_graph_relations, search_chapters, \
get_relations_to_level_simple, get_chapter_relations
router = APIRouter(
prefix="/chapters",
tags=["Chapters"],
)
@router.post("/relation/", response_model=ChapterRelationResponse)
def add_chapter_relation(relation: ChapterRelationCreate):
"""
创建章节之间的关系
"""
return create_chapter_relation(relation)
@router.get("/relations/", response_model=List[ChapterRelationResponse])
def list_chapter_relations():
"""
查询所有章节关系
"""
return get_graph_relations()
@router.get("/search_chapters", response_model=List[ChapterRelationResponse])
def search_chapters_endpoint(q: str):
"""
API 端点:根据搜索关键字模糊查询章节及其相关章节
:param q: 搜索关键字
:return: 匹配的章节关系列表
"""
if not q:
raise HTTPException(status_code=400, detail="搜索关键字不能为空")
results = search_chapters(q)
if not results:
raise HTTPException(status_code=404, detail="未找到匹配的章节关系")
return results
@router.get("/relations/level/{level}", response_model=List[ChapterRelationResponse])
def get_relations_by_level_simple(level: int):
"""
简化版:根据目标层级查询从 Root 到目标层级的所有节点和关系
:param level: 目标层级1 -> Root & Subject, 2 -> Root, Subject, Topic, ..., 5 -> Problem
:return: 对应层级的节点和关系
"""
if level < 0 or level > 5:
raise HTTPException(status_code=400, detail="层级参数必须在 0 到 5 之间")
try:
relations = get_relations_to_level_simple(level)
if not relations:
raise HTTPException(status_code=404, detail="未找到相关节点关系")
return relations
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("/{chapter}/relations", response_model=List[ChapterRelationResponse])
async def get_relations_by_chapter(chapter: str):
"""
根据章节名称获取该章节及其相关关系,但排除 label 为 Subject 的 next_SB 关系
:param chapter_name: 章节名称
:return: 章节关系列表
"""
try:
relations = get_chapter_relations(chapter)
if not relations:
raise HTTPException(status_code=404, detail=f"No relations found for chapter {chapter}")
return relations
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching relations: {str(e)}")