xuguoyang 9 月之前
父节点
当前提交
43f6902361

+ 4 - 0
routers/api/__init__.py

@@ -16,6 +16,8 @@ from . import emergencyPlans
 from . import eventManagement
 from . import spatialAnalysis
 from . import taskRegistration
+from . import riskMonitor
+from . import temperaturePrecipitation
 from . import pattern
 from . import rainfall
 from routers.prod_api import system
@@ -39,6 +41,8 @@ router.include_router(videoResource.router, prefix="/videoResource")
 router.include_router(Knowledge.router, prefix="/knowledge")
 router.include_router(taskRegistration.router, prefix="/taskRegistration")
 router.include_router(emergencyPlans.router, prefix="/emergency_plan")
+router.include_router(riskMonitor.router, prefix="/risk_monitor")
+router.include_router(temperaturePrecipitation.router, prefix="/temperature_precipitation")
 
 router.include_router(eventManagement.router, prefix="/event_management", tags=["事件管理"])
 router.include_router(spatialAnalysis.router, prefix="/spatial_analysis", tags=["空间分析"])

+ 11 - 0
routers/api/riskMonitor/__init__.py

@@ -0,0 +1,11 @@
+from fastapi import APIRouter
+from . import rain_condition
+from . import forest_fire_condition
+from . import  hazardous_condition
+
+
+router = APIRouter()
+
+router.include_router(rain_condition.router, prefix="/rain", tags=["雨情"])
+router.include_router(forest_fire_condition.router, prefix="/forest", tags=["森林"])
+router.include_router(hazardous_condition.router, prefix="/hazardous", tags=["危化品"])

+ 126 - 0
routers/api/riskMonitor/forest_fire_condition.py

@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
+from common.security import valid_access_token
+from sqlalchemy.orm import Session
+from sqlalchemy.sql import func
+from common.auth_user import *
+from sqlalchemy import  text
+from pydantic import BaseModel
+from common.BigDataCenterAPI import *
+from database import get_db
+from typing import List
+from utils import *
+from utils.risk import *
+import json
+import traceback
+
+router = APIRouter()
+
+
+
+@router.post('/get_max_forest')
+async def mine(request: Request,db: Session = Depends(get_db)):
+    try:
+        body = await request.json()
+        result = get_max_forest_level(db)
+        print(result)
+        result = get_warning_description(result)
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data":
+                {"max_level":result}
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
+
+
+
+def get_warning_description(level):
+    if level == 1:
+        return "无危险"
+    elif level == 2:
+        return "较低危险"
+    elif level == 3:
+        return "中等危险"
+    elif level == 4:
+        return "高火险级"
+    elif level == 5:
+        return "最高火险级"
+    else:
+        return "未知等级"
+
+
+@router.post('/forest_warrning')
+async def mine(request: Request,db: Session = Depends(get_db)):
+    try:
+        body = await request.json()
+
+
+
+        max_time = get_forest_max_time(db)
+        result = ''
+
+
+        forest_warring = get_forest_warring(db)
+        print(forest_warring)
+
+        # 分析数据
+        high_risk_areas = []
+        medium_risk_areas = []
+        low_risk_areas = []
+
+        all_low_risk = True  # 假设所有区域都是低风险
+
+        for item in forest_warring:
+            if item['warning_level'] >= 2:  # 只考虑等级大于等于2的
+                all_low_risk = False
+                level_description = get_warning_description(item['warning_level'])
+                area_report = f"{item['area_name']}的森林火险等级为{level_description}({item['warning_level']}级)"
+                if item['warning_level'] == 2:
+                    low_risk_areas.append(area_report)
+                elif item['warning_level'] == 3:
+                    medium_risk_areas.append(area_report)
+                elif item['warning_level'] >= 4:
+                    high_risk_areas.append(area_report)
+
+        # 构建描述句子
+        if all_low_risk:
+            risk_description = "当前无风险"
+        else:
+            risk_description = ""
+            if high_risk_areas:
+                risk_description += ";".join(high_risk_areas)
+            if medium_risk_areas:
+                if risk_description:
+                    risk_description += ";"
+                risk_description += ";".join(medium_risk_areas)
+            if low_risk_areas:
+                if risk_description:
+                    risk_description += ";"
+                risk_description += ";".join(low_risk_areas)
+        result = ''
+        # 输出结果
+        if risk_description:
+            result = f"{max_time},{risk_description}"
+        else:
+            result =f"{max_time},当前无风险"
+
+
+        print(result)
+
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data":
+                {"result":result}
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
+

+ 95 - 0
routers/api/riskMonitor/hazardous_condition.py

@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
+from common.security import valid_access_token
+from sqlalchemy.orm import Session
+from sqlalchemy.sql import func
+from common.auth_user import *
+from sqlalchemy import  text
+from pydantic import BaseModel
+from common.BigDataCenterAPI import *
+from database import get_db
+from typing import List
+from utils import *
+from utils.risk import *
+import json
+import traceback
+
+router = APIRouter()
+
+
+
+@router.post('/get_max_hazardous')
+async def mine(request: Request,db: Session = Depends(get_db)):
+    try:
+        body = await request.json()
+        result = get_max_forest_level(db)
+        print(result)
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data":
+                {"max_level":result}
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
+
+
+
+def get_warning_description(level):
+    if level == 1:
+        return "无危险"
+    elif level == 2:
+        return "较低危险"
+    elif level == 3:
+        return "中等危险"
+    elif level == 4:
+        return "高火险级"
+    elif level == 5:
+        return "最高火险级"
+    else:
+        return "未知等级"
+
+
+@router.post('/hazardous_warrning')
+async def mine(request: Request,db: Session = Depends(get_db)):
+    try:
+
+        result = "当前预警等级较高的风险区域:"+"电白区、信宜市"
+
+        print(result)
+
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data":
+                {"result":"较大风险"}
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
+
+
+@router.post('/hazardous_warrning_count')
+async def mine(request: Request,db: Session = Depends(get_db)):
+    try:
+
+        result = get_hazardous_warring_count(db)
+
+        print(result)
+
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data":
+                {"result":result}
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
+

+ 69 - 0
routers/api/temperaturePrecipitation/__init__.py

@@ -0,0 +1,69 @@
+from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
+from common.security import valid_access_token
+from sqlalchemy.orm import Session
+from sqlalchemy.sql import func
+from common.auth_user import *
+from sqlalchemy import  text
+from pydantic import BaseModel
+from common.BigDataCenterAPI import *
+from database import get_db
+from typing import List
+from utils import *
+from utils.risk import *
+import json
+import traceback
+
+router = APIRouter()
+
+
+
+@router.post('/temperature')
+async def mine(request: Request,db: Session = Depends(get_db)):
+    try:
+        body = await request.json()
+        args = body.get("args")
+        print(args)
+        result = []
+        if args == "6h_precipitation":
+            result.append(
+                {"create_time":"",
+                 "pic_url":"https://soc.gd121.cn/sk6hrain/2024/10/MSP1_AGD_MANOBS_PRCPV_L88_AGD_202410070100_00600-00000.PNG"}
+            )
+        elif args == "24h_precipitation":
+            result.append(
+                {"create_time": "",
+                 "pic_url": "https://soc.gd121.cn/sk24hrain/2024/10/MSP1_AGD_MANOBS_PRCPV_L88_AGD_202410070100_02400-00000.PNG"}
+            )
+        elif args == "hourly_temperature":
+            result.append(
+                {"create_time": "",
+                 "pic_url": "https://soc.gd121.cn/skt/2024/10/MSP1_AGD_MANOBS_T_L88_AGD_202410062300_00000-00000.PNG"}
+            )
+        elif args == "24h_max_temperature":
+            result.append(
+                {"create_time": "",
+                 "pic_url": "https://soc.gd121.cn/sk24htmax/2024/10/MSP1_AGD_MANOBS_TMA_L88_AGD_202410062300_02400-00000.PNG"}
+            )
+        elif args == "24h_min_temperature":
+            result.append(
+                {"create_time": "",
+                 "pic_url": "https://soc.gd121.cn/sk24htmin/2024/10/MSP1_AGD_MANOBS_TMI_L88_AGD_202410070100_02400-00000.PNG"}
+            )
+        elif args == "24h_variable_temperature":
+            result.append(
+                {"create_time": "",
+                 "pic_url": "https://soc.gd121.cn/sk24htmin/2024/10/MSP1_AGD_MANOBS_TMI_L88_AGD_202410070100_02400-00000.PNG"}
+            )
+
+
+        print(result)
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data":
+                {"max_level":result}
+        }
+    except Exception as e:
+        db.rollback()
+        traceback.print_exc()
+        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

+ 120 - 3
utils/risk/__init__.py

@@ -88,8 +88,7 @@ END,'0'))T2 on T1.`name`=T2.`name`;
         })
     return resutl
 
-def get_max_time(db):
-    resutl = []
+def get_rain_max_time(db):
     sql = text(f"""
         SELECT MAX(CREATE_TIME) FROM govdata_rain_data_info;
 """)
@@ -99,6 +98,16 @@ def get_max_time(db):
 
     return formatted_dt
 
+def get_forest_max_time(db):
+    sql = text(f"""
+        SELECT MAX(CREATE_TIME) FROM forest_fire;
+""")
+
+    sqlresult = db.execute(sql).first()[0]
+    formatted_dt = sqlresult.strftime('%Y-%m-%d %H:%M')
+
+    return formatted_dt
+
 def get_max_rain_township(db):
     resutl = []
     sql = text(f"""
@@ -137,4 +146,112 @@ LIMIT 1;
             'township':i[1],
             'rn':i[2]
         })
-    return resutl
+    return resutl
+
+
+def get_max_forest_level(db):
+    sql = '''
+        SELECT MAX(subquery.warning_level) as max_level
+        FROM (
+            SELECT 
+                AREA_NAME,
+                create_time,
+                  warning_level,
+                ROW_NUMBER() OVER (PARTITION BY AREA_CODE ORDER BY create_time DESC) AS rn
+            FROM 
+                `forest_fire`
+        ) AS subquery
+        WHERE rn = 1;
+    '''
+    sqlresult = db.execute(sql).first()[0]
+    return sqlresult
+
+
+def get_forest_warring(db):
+    result = []
+    sql=''' SELECT *
+        FROM (
+            SELECT 
+                AREA_NAME,
+                create_time,
+                  warning_level,
+                ROW_NUMBER() OVER (PARTITION BY AREA_CODE ORDER BY create_time DESC) AS rn
+            FROM 
+                `forest_fire`
+        ) AS subquery
+        WHERE rn = 1;
+				    '''
+    sqlresult = db.execute(sql)
+    for i in sqlresult:
+        print(i)
+        result.append({
+            'area_name': i[0],
+            'warning_level': i[2],
+            'rn': i[3]
+        })
+    return result
+
+
+
+
+def get_max_hazardous_level(db):
+    sql = '''
+        SELECT MAX(subquery.warning_level) as max_level
+        FROM (
+            SELECT 
+                AREA_NAME,
+                create_time,
+                  warning_level,
+                ROW_NUMBER() OVER (PARTITION BY AREA_CODE ORDER BY create_time DESC) AS rn
+            FROM 
+                `hazardous_chemicals`
+        ) AS subquery
+        WHERE rn = 1;
+    '''
+    sqlresult = db.execute(sql).first()[0]
+    return sqlresult
+
+
+def get_hazardous_warring(db):
+    result = []
+    sql=''' SELECT *
+        FROM (
+            SELECT 
+                AREA_NAME,
+                create_time,
+                  warning_level,
+                ROW_NUMBER() OVER (PARTITION BY AREA_CODE ORDER BY create_time DESC) AS rn
+            FROM 
+                `hazardous_chemicals`
+        ) AS subquery
+        WHERE rn = 1;
+				    '''
+    sqlresult = db.execute(sql)
+    for i in sqlresult:
+        print(i)
+        result.append({
+            'area_name': i[0],
+            'warning_level': i[2],
+            'rn': i[3]
+        })
+    return result
+
+
+def get_hazardous_warring_count(db):
+    result = []
+    sql=''' 
+        SELECT '重大风险' AS LEVEL,0 AS VAL
+        UNION ALL
+        SELECT '较大风险' AS LEVEL,5 AS VAL
+        UNION ALL
+        SELECT '一般风险' AS LEVEL,6 AS VAL
+        UNION ALL
+        SELECT '低风险' AS LEVEL,23 AS VAL
+				    '''
+    sqlresult = db.execute(sql)
+    for i in sqlresult:
+        print(i)
+        result.append({
+            'LEVEL': i[0],
+            'VALUES': i[1]})
+    return result