cd_prediction.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. """
  2. Cd预测模型API接口
  3. @description: 提供作物Cd和有效态Cd的预测与可视化功能
  4. """
  5. from fastapi import APIRouter, HTTPException, BackgroundTasks
  6. from fastapi.responses import FileResponse
  7. from typing import Dict, Any
  8. import os
  9. import logging
  10. from ..services.cd_prediction_service import CdPredictionService
  11. router = APIRouter()
  12. # 设置日志
  13. logger = logging.getLogger(__name__)
  14. @router.post("/crop-cd/generate-and-get-map",
  15. summary="一键生成并获取作物Cd预测地图",
  16. description="执行作物Cd模型预测,生成可视化地图后直接返回图片文件")
  17. async def generate_and_get_crop_cd_map():
  18. """
  19. 一键生成并获取作物Cd预测地图
  20. @returns {FileResponse} 作物Cd预测地图文件
  21. @throws {HTTPException} 当预测过程发生错误时抛出500错误
  22. @example
  23. >>> response = await generate_and_get_crop_cd_map()
  24. >>> # 直接返回图片文件,可在浏览器中查看或下载
  25. """
  26. try:
  27. logger.info("开始一键生成作物Cd预测地图")
  28. service = CdPredictionService()
  29. result = await service.generate_crop_cd_prediction()
  30. if not result['map_path'] or not os.path.exists(result['map_path']):
  31. raise HTTPException(
  32. status_code=500,
  33. detail="地图文件生成失败"
  34. )
  35. logger.info(f"作物Cd预测地图生成成功,直接返回文件: {result['map_path']}")
  36. return FileResponse(
  37. path=result['map_path'],
  38. filename="crop_cd_prediction_map.jpg",
  39. media_type="image/jpeg"
  40. )
  41. except Exception as e:
  42. logger.error(f"一键生成作物Cd预测地图失败: {str(e)}")
  43. raise HTTPException(
  44. status_code=500,
  45. detail=f"一键生成作物Cd预测地图失败: {str(e)}"
  46. )
  47. @router.post("/effective-cd/generate-and-get-map",
  48. summary="一键生成并获取有效态Cd预测地图",
  49. description="执行有效态Cd模型预测,生成可视化地图后直接返回图片文件")
  50. async def generate_and_get_effective_cd_map():
  51. """
  52. 一键生成并获取有效态Cd预测地图
  53. @returns {FileResponse} 有效态Cd预测地图文件
  54. @throws {HTTPException} 当预测过程发生错误时抛出500错误
  55. @example
  56. >>> response = await generate_and_get_effective_cd_map()
  57. >>> # 直接返回图片文件,可在浏览器中查看或下载
  58. """
  59. try:
  60. logger.info("开始一键生成有效态Cd预测地图")
  61. service = CdPredictionService()
  62. result = await service.generate_effective_cd_prediction()
  63. if not result['map_path'] or not os.path.exists(result['map_path']):
  64. raise HTTPException(
  65. status_code=500,
  66. detail="地图文件生成失败"
  67. )
  68. logger.info(f"有效态Cd预测地图生成成功,直接返回文件: {result['map_path']}")
  69. return FileResponse(
  70. path=result['map_path'],
  71. filename="effective_cd_prediction_map.jpg",
  72. media_type="image/jpeg"
  73. )
  74. except Exception as e:
  75. logger.error(f"一键生成有效态Cd预测地图失败: {str(e)}")
  76. raise HTTPException(
  77. status_code=500,
  78. detail=f"一键生成有效态Cd预测地图失败: {str(e)}"
  79. )
  80. @router.post("/crop-cd/generate-and-get-histogram",
  81. summary="一键生成并获取作物Cd预测直方图",
  82. description="执行作物Cd模型预测,生成预测值分布直方图后直接返回图片文件")
  83. async def generate_and_get_crop_cd_histogram():
  84. """
  85. 一键生成并获取作物Cd预测直方图
  86. @returns {FileResponse} 作物Cd预测直方图文件
  87. @throws {HTTPException} 当预测过程发生错误时抛出500错误
  88. @example
  89. >>> response = await generate_and_get_crop_cd_histogram()
  90. >>> # 直接返回直方图文件,可在浏览器中查看或下载
  91. """
  92. try:
  93. logger.info("开始一键生成作物Cd预测直方图")
  94. service = CdPredictionService()
  95. result = await service.generate_crop_cd_prediction()
  96. if not result['histogram_path'] or not os.path.exists(result['histogram_path']):
  97. raise HTTPException(
  98. status_code=500,
  99. detail="直方图文件生成失败"
  100. )
  101. logger.info(f"作物Cd预测直方图生成成功,直接返回文件: {result['histogram_path']}")
  102. return FileResponse(
  103. path=result['histogram_path'],
  104. filename="crop_cd_prediction_histogram.jpg",
  105. media_type="image/jpeg"
  106. )
  107. except Exception as e:
  108. logger.error(f"一键生成作物Cd预测直方图失败: {str(e)}")
  109. raise HTTPException(
  110. status_code=500,
  111. detail=f"一键生成作物Cd预测直方图失败: {str(e)}"
  112. )
  113. @router.post("/effective-cd/generate-and-get-histogram",
  114. summary="一键生成并获取有效态Cd预测直方图",
  115. description="执行有效态Cd模型预测,生成预测值分布直方图后直接返回图片文件")
  116. async def generate_and_get_effective_cd_histogram():
  117. """
  118. 一键生成并获取有效态Cd预测直方图
  119. @returns {FileResponse} 有效态Cd预测直方图文件
  120. @throws {HTTPException} 当预测过程发生错误时抛出500错误
  121. @example
  122. >>> response = await generate_and_get_effective_cd_histogram()
  123. >>> # 直接返回直方图文件,可在浏览器中查看或下载
  124. """
  125. try:
  126. logger.info("开始一键生成有效态Cd预测直方图")
  127. service = CdPredictionService()
  128. result = await service.generate_effective_cd_prediction()
  129. if not result['histogram_path'] or not os.path.exists(result['histogram_path']):
  130. raise HTTPException(
  131. status_code=500,
  132. detail="直方图文件生成失败"
  133. )
  134. logger.info(f"有效态Cd预测直方图生成成功,直接返回文件: {result['histogram_path']}")
  135. return FileResponse(
  136. path=result['histogram_path'],
  137. filename="effective_cd_prediction_histogram.jpg",
  138. media_type="image/jpeg"
  139. )
  140. except Exception as e:
  141. logger.error(f"一键生成有效态Cd预测直方图失败: {str(e)}")
  142. raise HTTPException(
  143. status_code=500,
  144. detail=f"一键生成有效态Cd预测直方图失败: {str(e)}"
  145. )
  146. # 分步式接口 - 先生成后下载
  147. @router.post("/crop-cd/generate-map",
  148. summary="生成作物Cd预测地图",
  149. description="执行作物Cd模型预测并生成可视化地图")
  150. async def generate_crop_cd_map() -> Dict[str, Any]:
  151. """
  152. 生成作物Cd预测地图
  153. @returns {Dict[str, Any]} 包含地图文件路径和预测统计信息的响应
  154. @throws {HTTPException} 当预测过程发生错误时抛出500错误
  155. @example
  156. >>> response = await generate_crop_cd_map()
  157. >>> print(response['data']['map_path'])
  158. """
  159. try:
  160. logger.info("开始生成作物Cd预测地图")
  161. service = CdPredictionService()
  162. result = await service.generate_crop_cd_prediction()
  163. logger.info(f"作物Cd预测地图生成成功: {result['map_path']}")
  164. return {
  165. "success": True,
  166. "message": "作物Cd预测地图生成成功",
  167. "data": {
  168. "map_path": result['map_path'],
  169. "histogram_path": result['histogram_path'],
  170. "raster_path": result['raster_path'],
  171. "prediction_stats": result.get('stats', {})
  172. },
  173. "error": None
  174. }
  175. except Exception as e:
  176. logger.error(f"生成作物Cd预测地图失败: {str(e)}")
  177. raise HTTPException(
  178. status_code=500,
  179. detail=f"生成作物Cd预测地图失败: {str(e)}"
  180. )
  181. @router.post("/effective-cd/generate-map",
  182. summary="生成有效态Cd预测地图",
  183. description="执行有效态Cd模型预测并生成可视化地图")
  184. async def generate_effective_cd_map() -> Dict[str, Any]:
  185. """
  186. 生成有效态Cd预测地图
  187. @returns {Dict[str, Any]} 包含地图文件路径和预测统计信息的响应
  188. @throws {HTTPException} 当预测过程发生错误时抛出500错误
  189. @example
  190. >>> response = await generate_effective_cd_map()
  191. >>> print(response['data']['map_path'])
  192. """
  193. try:
  194. logger.info("开始生成有效态Cd预测地图")
  195. service = CdPredictionService()
  196. result = await service.generate_effective_cd_prediction()
  197. logger.info(f"有效态Cd预测地图生成成功: {result['map_path']}")
  198. return {
  199. "success": True,
  200. "message": "有效态Cd预测地图生成成功",
  201. "data": {
  202. "map_path": result['map_path'],
  203. "histogram_path": result['histogram_path'],
  204. "raster_path": result['raster_path'],
  205. "prediction_stats": result.get('stats', {})
  206. },
  207. "error": None
  208. }
  209. except Exception as e:
  210. logger.error(f"生成有效态Cd预测地图失败: {str(e)}")
  211. raise HTTPException(
  212. status_code=500,
  213. detail=f"生成有效态Cd预测地图失败: {str(e)}"
  214. )
  215. @router.get("/crop-cd/download-map",
  216. summary="下载作物Cd预测地图",
  217. description="下载最新生成的作物Cd预测地图文件")
  218. async def download_crop_cd_map():
  219. """
  220. 下载作物Cd预测地图文件
  221. @returns {FileResponse} 作物Cd预测地图文件
  222. @throws {HTTPException} 当地图文件不存在时抛出404错误
  223. """
  224. try:
  225. service = CdPredictionService()
  226. map_path = service.get_latest_crop_cd_map()
  227. if not map_path or not os.path.exists(map_path):
  228. raise HTTPException(
  229. status_code=404,
  230. detail="作物Cd预测地图文件不存在,请先生成地图"
  231. )
  232. return FileResponse(
  233. path=map_path,
  234. filename="crop_cd_prediction_map.jpg",
  235. media_type="image/jpeg"
  236. )
  237. except Exception as e:
  238. logger.error(f"下载作物Cd预测地图失败: {str(e)}")
  239. raise HTTPException(
  240. status_code=500,
  241. detail=f"下载作物Cd预测地图失败: {str(e)}"
  242. )
  243. @router.get("/effective-cd/download-map",
  244. summary="下载有效态Cd预测地图",
  245. description="下载最新生成的有效态Cd预测地图文件")
  246. async def download_effective_cd_map():
  247. """
  248. 下载有效态Cd预测地图文件
  249. @returns {FileResponse} 有效态Cd预测地图文件
  250. @throws {HTTPException} 当地图文件不存在时抛出404错误
  251. """
  252. try:
  253. service = CdPredictionService()
  254. map_path = service.get_latest_effective_cd_map()
  255. if not map_path or not os.path.exists(map_path):
  256. raise HTTPException(
  257. status_code=404,
  258. detail="有效态Cd预测地图文件不存在,请先生成地图"
  259. )
  260. return FileResponse(
  261. path=map_path,
  262. filename="effective_cd_prediction_map.jpg",
  263. media_type="image/jpeg"
  264. )
  265. except Exception as e:
  266. logger.error(f"下载有效态Cd预测地图失败: {str(e)}")
  267. raise HTTPException(
  268. status_code=500,
  269. detail=f"下载有效态Cd预测地图失败: {str(e)}"
  270. )
  271. @router.get("/crop-cd/download-histogram",
  272. summary="下载作物Cd预测直方图",
  273. description="下载最新生成的作物Cd预测值分布直方图")
  274. async def download_crop_cd_histogram():
  275. """
  276. 下载作物Cd预测直方图文件
  277. @returns {FileResponse} 作物Cd预测直方图文件
  278. @throws {HTTPException} 当直方图文件不存在时抛出404错误
  279. """
  280. try:
  281. service = CdPredictionService()
  282. histogram_path = service.get_latest_crop_cd_histogram()
  283. if not histogram_path or not os.path.exists(histogram_path):
  284. raise HTTPException(
  285. status_code=404,
  286. detail="作物Cd预测直方图文件不存在,请先生成图表"
  287. )
  288. return FileResponse(
  289. path=histogram_path,
  290. filename="crop_cd_prediction_histogram.jpg",
  291. media_type="image/jpeg"
  292. )
  293. except Exception as e:
  294. logger.error(f"下载作物Cd预测直方图失败: {str(e)}")
  295. raise HTTPException(
  296. status_code=500,
  297. detail=f"下载作物Cd预测直方图失败: {str(e)}"
  298. )
  299. @router.get("/effective-cd/download-histogram",
  300. summary="下载有效态Cd预测直方图",
  301. description="下载最新生成的有效态Cd预测值分布直方图")
  302. async def download_effective_cd_histogram():
  303. """
  304. 下载有效态Cd预测直方图文件
  305. @returns {FileResponse} 有效态Cd预测直方图文件
  306. @throws {HTTPException} 当直方图文件不存在时抛出404错误
  307. """
  308. try:
  309. service = CdPredictionService()
  310. histogram_path = service.get_latest_effective_cd_histogram()
  311. if not histogram_path or not os.path.exists(histogram_path):
  312. raise HTTPException(
  313. status_code=404,
  314. detail="有效态Cd预测直方图文件不存在,请先生成图表"
  315. )
  316. return FileResponse(
  317. path=histogram_path,
  318. filename="effective_cd_prediction_histogram.jpg",
  319. media_type="image/jpeg"
  320. )
  321. except Exception as e:
  322. logger.error(f"下载有效态Cd预测直方图失败: {str(e)}")
  323. raise HTTPException(
  324. status_code=500,
  325. detail=f"下载有效态Cd预测直方图失败: {str(e)}"
  326. )