ppchatocrv3.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import List, Literal, Optional, Union
  15. from fastapi import FastAPI, HTTPException
  16. from pydantic import BaseModel, Field
  17. from typing_extensions import Annotated, TypeAlias, assert_never
  18. from .....utils import logging
  19. from .... import results
  20. from ...ppchatocrv3 import PPChatOCRPipeline
  21. from .. import utils as serving_utils
  22. from ..app import AppConfig, create_app
  23. from ..models import NoResultResponse, ResultResponse, DataInfo
  24. from ._common import ocr as ocr_common
  25. class AnalyzeImagesRequest(ocr_common.InferRequest):
  26. useImgOrientationCls: bool = True
  27. useImgUnwarping: bool = True
  28. useSealTextDet: bool = True
  29. Point: TypeAlias = Annotated[List[int], Field(min_length=2, max_length=2)]
  30. Polygon: TypeAlias = Annotated[List[Point], Field(min_length=3)]
  31. BoundingBox: TypeAlias = Annotated[List[float], Field(min_length=4, max_length=4)]
  32. class Text(BaseModel):
  33. poly: Polygon
  34. text: str
  35. score: float
  36. class Table(BaseModel):
  37. bbox: BoundingBox
  38. html: str
  39. class VisionResult(BaseModel):
  40. texts: List[Text]
  41. tables: List[Table]
  42. inputImage: str
  43. ocrImage: str
  44. layoutImage: str
  45. class AnalyzeImagesResult(BaseModel):
  46. visionResults: List[VisionResult]
  47. visionInfo: dict
  48. dataInfo: DataInfo
  49. class QianfanParams(BaseModel):
  50. apiKey: str
  51. secretKey: str
  52. apiType: Literal["qianfan"] = "qianfan"
  53. class AIStudioParams(BaseModel):
  54. accessToken: str
  55. apiType: Literal["aistudio"] = "aistudio"
  56. LLMName: TypeAlias = Literal[
  57. "ernie-3.5",
  58. "ernie-3.5-8k",
  59. "ernie-lite",
  60. "ernie-4.0",
  61. "ernie-4.0-turbo-8k",
  62. "ernie-speed",
  63. "ernie-speed-128k",
  64. "ernie-tiny-8k",
  65. "ernie-char-8k",
  66. ]
  67. LLMParams: TypeAlias = Union[QianfanParams, AIStudioParams]
  68. class BuildVectorStoreRequest(BaseModel):
  69. visionInfo: dict
  70. minChars: Optional[int] = None
  71. llmRequestInterval: Optional[float] = None
  72. llmName: Optional[LLMName] = None
  73. llmParams: Optional[Annotated[LLMParams, Field(discriminator="apiType")]] = None
  74. class BuildVectorStoreResult(BaseModel):
  75. vectorStore: str
  76. class RetrieveKnowledgeRequest(BaseModel):
  77. keys: List[str]
  78. vectorStore: str
  79. llmName: Optional[LLMName] = None
  80. llmParams: Optional[Annotated[LLMParams, Field(discriminator="apiType")]] = None
  81. class RetrieveKnowledgeResult(BaseModel):
  82. retrievalResult: str
  83. class ChatRequest(BaseModel):
  84. keys: List[str]
  85. visionInfo: dict
  86. vectorStore: Optional[str] = None
  87. retrievalResult: Optional[str] = None
  88. taskDescription: Optional[str] = None
  89. rules: Optional[str] = None
  90. fewShot: Optional[str] = None
  91. llmName: Optional[LLMName] = None
  92. llmParams: Optional[Annotated[LLMParams, Field(discriminator="apiType")]] = None
  93. returnPrompts: bool = False
  94. class Prompts(BaseModel):
  95. ocr: List[str]
  96. table: Optional[List[str]] = None
  97. html: Optional[List[str]] = None
  98. class ChatResult(BaseModel):
  99. chatResult: dict
  100. prompts: Optional[Prompts] = None
  101. def _llm_params_to_dict(llm_params: LLMParams) -> dict:
  102. if llm_params.apiType == "qianfan":
  103. return {
  104. "api_type": "qianfan",
  105. "ak": llm_params.apiKey,
  106. "sk": llm_params.secretKey,
  107. }
  108. if llm_params.apiType == "aistudio":
  109. return {"api_type": "aistudio", "access_token": llm_params.accessToken}
  110. else:
  111. assert_never(llm_params.apiType)
  112. def create_pipeline_app(pipeline: PPChatOCRPipeline, app_config: AppConfig) -> FastAPI:
  113. app, ctx = create_app(
  114. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  115. )
  116. ocr_common.update_app_context(ctx)
  117. @app.post(
  118. "/chatocr-vision",
  119. operation_id="analyzeImages",
  120. responses={422: {"model": NoResultResponse}},
  121. response_model_exclude_none=True,
  122. )
  123. async def _analyze_images(
  124. request: AnalyzeImagesRequest,
  125. ) -> ResultResponse[AnalyzeImagesResult]:
  126. pipeline = ctx.pipeline
  127. log_id = serving_utils.generate_log_id()
  128. if request.inferenceParams:
  129. max_long_side = request.inferenceParams.maxLongSide
  130. if max_long_side:
  131. raise HTTPException(
  132. status_code=422,
  133. detail="`max_long_side` is currently not supported.",
  134. )
  135. images, data_info = await ocr_common.get_images(request, ctx)
  136. try:
  137. result = await pipeline.call(
  138. pipeline.pipeline.visual_predict,
  139. images,
  140. use_doc_image_ori_cls_model=request.useImgOrientationCls,
  141. use_doc_image_unwarp_model=request.useImgUnwarping,
  142. use_seal_text_det_model=request.useSealTextDet,
  143. )
  144. vision_results: List[VisionResult] = []
  145. for i, (img, item) in enumerate(zip(images, result[0])):
  146. texts: List[Text] = []
  147. for poly, text, score in zip(
  148. item["ocr_result"]["dt_polys"],
  149. item["ocr_result"]["rec_text"],
  150. item["ocr_result"]["rec_score"],
  151. ):
  152. texts.append(Text(poly=poly, text=text, score=score))
  153. tables = [
  154. Table(bbox=r["layout_bbox"], html=r["html"])
  155. for r in item["table_result"]
  156. ]
  157. input_img, layout_img, ocr_img = await ocr_common.postprocess_images(
  158. log_id=log_id,
  159. index=i,
  160. app_context=ctx,
  161. input_image=img,
  162. layout_image=item["layout_result"].img,
  163. ocr_image=item["ocr_result"].img,
  164. )
  165. vision_result = VisionResult(
  166. texts=texts,
  167. tables=tables,
  168. inputImage=input_img,
  169. ocrImage=ocr_img,
  170. layoutImage=layout_img,
  171. )
  172. vision_results.append(vision_result)
  173. return ResultResponse[AnalyzeImagesResult](
  174. logId=log_id,
  175. result=AnalyzeImagesResult(
  176. visionResults=vision_results,
  177. visionInfo=result[1],
  178. dataInfo=data_info,
  179. ),
  180. )
  181. except Exception:
  182. logging.exception("Unexpected exception")
  183. raise HTTPException(status_code=500, detail="Internal server error")
  184. @app.post(
  185. "/chatocr-vector",
  186. operation_id="buildVectorStore",
  187. responses={422: {"model": NoResultResponse}},
  188. response_model_exclude_none=True,
  189. )
  190. async def _build_vector_store(
  191. request: BuildVectorStoreRequest,
  192. ) -> ResultResponse[BuildVectorStoreResult]:
  193. pipeline = ctx.pipeline
  194. try:
  195. kwargs = {"visual_info": results.VisualInfoResult(request.visionInfo)}
  196. if request.minChars is not None:
  197. kwargs["min_characters"] = request.minChars
  198. if request.llmRequestInterval is not None:
  199. kwargs["llm_request_interval"] = request.llmRequestInterval
  200. if request.llmName is not None:
  201. kwargs["llm_name"] = request.llmName
  202. if request.llmParams is not None:
  203. kwargs["llm_params"] = _llm_params_to_dict(request.llmParams)
  204. result = await serving_utils.call_async(
  205. pipeline.pipeline.build_vector, **kwargs
  206. )
  207. return ResultResponse[BuildVectorStoreResult](
  208. logId=serving_utils.generate_log_id(),
  209. result=BuildVectorStoreResult(vectorStore=result["vector"]),
  210. )
  211. except Exception:
  212. logging.exception("Unexpected exception")
  213. raise HTTPException(status_code=500, detail="Internal server error")
  214. @app.post(
  215. "/chatocr-retrieval",
  216. operation_id="retrieveKnowledge",
  217. responses={422: {"model": NoResultResponse}},
  218. response_model_exclude_none=True,
  219. )
  220. async def _retrieve_knowledge(
  221. request: RetrieveKnowledgeRequest,
  222. ) -> ResultResponse[RetrieveKnowledgeResult]:
  223. pipeline = ctx.pipeline
  224. try:
  225. kwargs = {
  226. "key_list": request.keys,
  227. "vector": results.VectorResult({"vector": request.vectorStore}),
  228. }
  229. if request.llmName is not None:
  230. kwargs["llm_name"] = request.llmName
  231. if request.llmParams is not None:
  232. kwargs["llm_params"] = _llm_params_to_dict(request.llmParams)
  233. result = await serving_utils.call_async(
  234. pipeline.pipeline.retrieval, **kwargs
  235. )
  236. return ResultResponse[RetrieveKnowledgeResult](
  237. logId=serving_utils.generate_log_id(),
  238. result=RetrieveKnowledgeResult(retrievalResult=result["retrieval"]),
  239. )
  240. except Exception:
  241. logging.exception("Unexpected exception")
  242. raise HTTPException(status_code=500, detail="Internal server error")
  243. @app.post(
  244. "/chatocr-chat",
  245. operation_id="chat",
  246. responses={422: {"model": NoResultResponse}},
  247. response_model_exclude_none=True,
  248. )
  249. async def _chat(
  250. request: ChatRequest,
  251. ) -> ResultResponse[ChatResult]:
  252. pipeline = ctx.pipeline
  253. try:
  254. kwargs = {
  255. "key_list": request.keys,
  256. "visual_info": results.VisualInfoResult(request.visionInfo),
  257. }
  258. if request.vectorStore is not None:
  259. kwargs["vector"] = results.VectorResult({"vector": request.vectorStore})
  260. if request.retrievalResult is not None:
  261. kwargs["retrieval_result"] = results.RetrievalResult(
  262. {"retrieval": request.retrievalResult}
  263. )
  264. if request.taskDescription is not None:
  265. kwargs["user_task_description"] = request.taskDescription
  266. if request.rules is not None:
  267. kwargs["rules"] = request.rules
  268. if request.fewShot is not None:
  269. kwargs["few_shot"] = request.fewShot
  270. if request.llmName is not None:
  271. kwargs["llm_name"] = request.llmName
  272. if request.llmParams is not None:
  273. kwargs["llm_params"] = _llm_params_to_dict(request.llmParams)
  274. kwargs["save_prompt"] = request.returnPrompts
  275. result = await serving_utils.call_async(pipeline.pipeline.chat, **kwargs)
  276. if result["prompt"]:
  277. prompts = Prompts(
  278. ocr=result["prompt"]["ocr_prompt"],
  279. table=result["prompt"]["table_prompt"] or None,
  280. html=result["prompt"]["html_prompt"] or None,
  281. )
  282. else:
  283. prompts = None
  284. chat_result = ChatResult(
  285. chatResult=result["chat_res"],
  286. prompts=prompts,
  287. )
  288. return ResultResponse[ChatResult](
  289. logId=serving_utils.generate_log_id(),
  290. result=chat_result,
  291. )
  292. except Exception:
  293. logging.exception("Unexpected exception")
  294. raise HTTPException(status_code=500, detail="Internal server error")
  295. return app