api_get_article2.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. from fastapi import FastAPI, Form, HTTPException, Request,status,APIRouter,Query,Path, Depends
  3. from tools.loglog import logger,log_err_e
  4. from core.respone_format import *
  5. from gpt.get_article2 import GetArticle
  6. from pydantic import BaseModel, ValidationError, conint,Field,conint
  7. from typing import List, Optional,Literal
  8. import asyncio
  9. router = APIRouter()
  10. async def get_article_dependency():
  11. article_generator = GetArticle()
  12. try:
  13. yield article_generator
  14. finally:
  15. await article_generator.cleanup()
  16. class Word(BaseModel):
  17. meaning_id:int = Field(..., description="单词的词义id")
  18. word_id:int = Field(..., description="单词id")
  19. spell: str = Field(..., description="单词的拼写")
  20. meaning: str = Field(..., description="单词的意思")
  21. class ArticleRequest(BaseModel):
  22. core_words: List[Word] = Field(..., description="单词列表")
  23. take_count: int = 2
  24. demo_name: Optional[str] = "无"
  25. reading_level: conint(ge=1, le=30) = Field(default=10, description="阅读水平,默认值为10;[8,16,24]小学初中高中")
  26. article_length:int = Field(default=None,description="需要生成的文章长度,可以不传,不传自己根据reading_level判断")
  27. exercise_id:int = Field(default=0,description="学案ID,用于日志快速定位")
  28. @router.post("/article/reading-comprehension")
  29. async def post_article(
  30. json_data:ArticleRequest,
  31. request:Request,
  32. get_article: GetArticle = Depends(get_article_dependency)
  33. ):
  34. """
  35. 异步处理文章生成请求
  36. """
  37. json_data = json_data.model_dump()
  38. real_ip = request.headers.get("X-Real-IP","0.0.0.0")
  39. core_words = json_data["core_words"]
  40. take_count = json_data["take_count"]
  41. demo_name = json_data["demo_name"]
  42. reading_level = json_data["reading_level"]
  43. article_length = json_data["article_length"]
  44. exercise_id = json_data["exercise_id"]
  45. try:
  46. r = await get_article.submit_task(
  47. real_ip=real_ip,
  48. core_words=core_words,
  49. take_count=take_count,
  50. demo_name=demo_name,
  51. reading_level=reading_level,
  52. article_length=article_length,
  53. exercise_id=exercise_id
  54. )
  55. return r if not isinstance(r,str) else resp_500(message=r)
  56. except Exception as e:
  57. log_err_e(e, msg="文章2接口错误/article/reading-comprehension;")
  58. return resp_500(message=f"{type(e).__name__},{e}")