Quellcode durchsuchen

阶段提交代码

yf_yzl vor 2 Jahren
Ursprung
Commit
0721bc7f85

BIN
bigdata_django/zhijian/__pycache__/cbd_single.cpython-36.pyc


BIN
bigdata_django/zhijian/__pycache__/cbd_zhijian.cpython-36.pyc


BIN
bigdata_django/zhijian/__pycache__/scd_zhijian.cpython-36.pyc


Datei-Diff unterdrückt, da er zu groß ist
+ 1078 - 0
bigdata_django/zhijian/cbd_single.py


Datei-Diff unterdrückt, da er zu groß ist
+ 1443 - 0
bigdata_django/zhijian/cbd_zhijian.py


Datei-Diff unterdrückt, da er zu groß ist
+ 1151 - 0
bigdata_django/zhijian/cbd_zhijian_nom.py


+ 30 - 0
bigdata_django/zhijian/pyflask/app.py

@@ -0,0 +1,30 @@
+from flask import Flask, request, jsonify
+from werkzeug.utils import secure_filename
+import os 
+
+app = Flask(__name__)
+
+UPLOAD_FOLDER = ''  # 上传文件保存的目录
+ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}  # 允许上传的图片文件类型
+
+app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
+
+def allowed_file(filename):
+    '''检查文件扩展名是否合法'''
+    return '.' in filename and \
+           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
+
+@app.route('/upload', methods=['POST'])
+def upload():
+    '''接收并保存上传的图片'''
+    file = request.files['file']
+
+    if file and allowed_file(file.filename):
+        filename = secure_filename(file.filename)
+        file.save(os.path.join(app.config['UPLOAD_FOLDER'], "1" + filename))
+        return jsonify({'result': 'Upload success.'})
+    else:
+        return jsonify({'error': 'Invalid file type.'})
+
+if __name__ == '__main__':
+    app.run()

+ 56 - 0
bigdata_django/zhijian/pyflask/send.py

@@ -0,0 +1,56 @@
+import time 
+import hashlib
+import requests
+import json
+from aliyunsdkcore.vendored.requests.auth import HTTPBasicAuth
+
+
+def sim_updata(iccid):
+    # 时间戳 用于获取sign
+    timestamp = int(time.time())
+    current_milli_time = lambda: int(round(time.time() * 1000))
+    data_1 = "appid=%s&iccid=%s&timestamp=%s%s"%("102420177762",iccid,current_milli_time(),"6397d7e6a56589f1d93284e9800493e1")
+    sign = hashlib.sha256(data_1.encode('utf-8')).hexdigest()
+    data = {"appid": "102420177762", "iccid": iccid, "timestamp":current_milli_time(),"sign":sign}
+    url  = "https://api.simboss.com/2.0/device/detail"    
+    try:
+        status = 1
+        ret = requests.post(url, data=data)
+        code = json.loads(ret.text)["code"]
+        if code == "0":
+            status = 1
+        else:
+            url = 'http://sim.brlink.cn/api/open/iotcard/card'
+            appkey = "iaO2DKgS8KdlnVgU"
+            appsecret = "qzKgO4sBdzMrjRwv9H22S9ufepNv8Hl5ehPqkYVD31DCICjyKwqUdj7zihQQKfgx"
+            status = 2
+            ret = requests.post(url,json={'iccid':iccid},auth=HTTPBasicAuth(appkey,appsecret),timeout=(5,10))
+            codes = json.loads(ret.text)["code"]
+            if codes == 0:
+                status = 2
+            else:
+                url = "https://jsnl.xmnengjia.com/open/api/module/cards"
+                data = {"iccids":[iccid]}
+                data = json.dumps(data)
+                ret = requests.post(url,data=data,timeout=(10,30))
+                print(ret.text)
+                status = 3
+    except:
+        status = 0
+        ret = 0
+    day = 0
+    if ret:
+        try:
+            result = json.loads(ret.text)
+            expiry_date = result.get("data", {}).get("expiry_date")
+            now_date = int(time.time())
+            day = int((expiry_date - now_date) / 3600 / 24) 
+        except:
+            return [0, "查询无结果"]
+    else:
+        return [0, "查询无结果"]
+    return [1, f"有效期剩余{day}天"]
+
+
+result = sim_updata("898604C51022D1285682")
+print(result)

+ 157 - 0
bigdata_django/zhijian/pyflask/utils.py

@@ -0,0 +1,157 @@
+import numpy as np
+import cv2
+# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
+"""
+Run a Flask REST API exposing one or more YOLOv5s models
+"""
+
+import argparse
+import io
+
+# import torch
+from PIL import Image
+from skimage import filters
+import os
+RESULT_FOLDER = './output_dir/nocutimg' #用于存放检测结果
+
+
+def draw(img,result,dstDir,filenameList,a):
+    """
+    为待检测图片 绘制矩形框和结果分数
+         Args:
+            img (list):利用opesncv按照字节读取的图片
+            result (list):检测结果的分数列表
+            dstDir (str):检测结果存放位置(./output_dir/nocutimg/exp_1/xxx.jpg)
+            filenameList (list):图片名
+            a:圆盘内接四边形坐标 (左上角,右上角)
+
+         return:
+    """
+    try:
+         os.makedirs(dstDir)
+    except:
+         pass
+    for i in range(len(filenameList)):
+        filename = os.path.join(dstDir,filenameList[i])
+        cv2.rectangle(img[i], (a[0], a[1]), (a[2], a[3]), (0, 0, 255), 2)
+        cv2.putText(img[i],"score:{}".format(result[i]), (30, 100),cv2.FONT_HERSHEY_PLAIN,7,(0,0,255),2)
+        cv2.imwrite(filename,img[i])
+    print("检查后图片已存入{}".format(dstDir))
+
+def _imageToMatrix(image):
+        """
+        根据名称读取图片对象转化矩阵
+        :param strName:
+        :return: 返回矩阵
+        """
+        imgMat = np.matrix(image)
+        return imgMat
+
+def preImgOps(img):
+        """
+        图像的预处理操作
+        :param img: 图像的而明朝
+        :return: 灰度化和resize之后的图片对象
+        """
+        # 预处理操作
+        reImg = cv2.resize(img, (300, 400), interpolation=cv2.INTER_CUBIC)  #
+        img2gray = cv2.cvtColor(reImg, cv2.COLOR_BGR2GRAY)  # 将图片压缩为单通道的灰度图
+        return reImg,img2gray
+
+def ReadImage(im_file):
+    """
+        读取图片
+        :param im_file: 图像的路径
+        :return: 利用opencv读取的完整图像img  托虫板内接四边形图像cutimg   内接四边形的坐标c[xmin,ymin,xmax,ymax] 
+    """
+    img = cv2.imdecode(np.fromfile(im_file, dtype=np.uint8), cv2.IMREAD_COLOR)
+    # imgfile = np.asarray(bytearray(im_file.read()), dtype="uint8")
+    # img = cv2.imdecode(imgfile, cv2.IMREAD_ANYCOLOR)
+    ImgShape = img.shape
+    print("原始图像大小{}".format(ImgShape))
+    center = [ImgShape[1]/2,ImgShape[0]/2] #圆盘中心
+    print("图像中心位置{}".format(center))
+    radius = int(ImgShape[0]/2) #圆盘半径
+    print("半径{}".format(radius))
+    length = pow(2,0.5)*radius    #圆的内接正方形边长
+    # print(length)
+    Size = int(length/2)
+    xmin = int(center[0] - Size)
+    xmax = int(center[0] + Size)
+    ymin = int((center[1] - Size)*1.1)
+    ymax = int(center[1] + Size)
+    c = [xmin,ymin,xmax,ymax]
+    # print(c)
+    cutimg = img[ymin:ymax,xmin:xmax]
+    # img = cv2.imdecode(imgfile, cv2.IMREAD_ANYCOLOR)
+    return img,cutimg,c
+
+def getFileName(imageFile):
+    url, FileName = os.path.split(imageFile)
+    # print(FileName)
+    tamp = []
+    tamp.append(FileName)
+    return tamp
+
+#图像清晰度检测
+def predict(imageFile):
+    """
+    图像清晰度检测
+    Args:
+        imageFile(dir or file):单张图片或者存放图片的文件夹
+    """
+    if not os.path.exists(RESULT_FOLDER):
+         os.makedirs(RESULT_FOLDER)
+    else:
+        pass
+    dirs = os.listdir(RESULT_FOLDER)
+    print(dirs)
+    print(imageFile)
+    # return str(len(dirs))
+    result = [] #存放清晰度评分
+    imgList = [] #存放识别后图片
+    if os.path.isdir(imageFile):
+        imageFileList = [os.path.join(imageFile,x) for x in os.listdir(imageFile)]
+        print("imageFileList",imageFileList)
+        for image in imageFileList:
+            print(image)
+            img,cutimg,c = ReadImage(image)
+            reImg, img2gray= preImgOps(cutimg)
+            f = _imageToMatrix(img2gray)
+
+            tmp = filters.sobel(f)
+            source=np.sum(tmp**2)
+            source=np.sqrt(source)
+            result.append(source)
+            imgList.append(img)
+        draw(imgList,result,RESULT_FOLDER+'/exp_'+str(len(dirs)+1)+"/", os.listdir(imageFile),c)
+    elif os.path.isfile(imageFile):
+            print("输入文件")
+            img,cutimg,c = ReadImage(imageFile)
+            reImg, img2gray= preImgOps(cutimg)
+            f = _imageToMatrix(img2gray)
+
+            tmp = filters.sobel(f)
+            source=np.sum(tmp**2)
+            source=np.sqrt(source)
+            result.append(source)
+            imgList.append(img)
+            draw(imgList,result,RESULT_FOLDER+'/exp_'+str(len(dirs)+1)+"/",getFileName(imageFile),c)
+    print(os.path.isdir(imageFile))
+    return result
+
+def main():
+    """
+       imageFile 文件夹或者文件 
+    """
+    # imageFile = "D:\\新建文件夹 (4)\\WeChat Files\\wxid_uqzo45cgfn1j12\\FileStorage\\File\\2023-06\\图片清晰度评分\\861551058842071-20230612141803.jpg"
+    # imageFile = "C:\\Users\\31453\\Desktop\\云飞代码\\imageQuiltyAssign-toyang\\predict\\861551054010806-20230512095242.jpg"
+    imageFile = r"E:\emo\output_dir\nocutimg"
+    predict(imageFile)
+
+if __name__ == '__main__':
+    """
+    使用说明:
+        修改main()函数中的imageFile:填入待检测图片url or 待检测图片文件夹url
+    """
+    main()

+ 80 - 29
bigdata_django/zhijian/scd_zhijian.py

@@ -8,9 +8,9 @@
 # run again.  Do not edit this file unless you know what you are doing.
 
 # pyinstaller -n "杀虫灯检验工具(v3.2)" -D -w f:\image_down_code\scd_zhijian.py -i .\LOGO.ico
-
+from aliyunsdkcore.vendored.requests.auth import HTTPBasicAuth
 from PyQt5 import QtCore, QtGui, QtWidgets
-
+import hashlib
 import os
 import sys
 import re
@@ -446,36 +446,66 @@ class SCDThread(QtCore.QThread):
         return d_id,deviceId,platform
     
     def sim_info(self,iccid):
-        """查询卡信息"""
-        url = "http://8.136.98.49:10001/iotcard/platsimview/inquiries/"
+        # 时间戳 用于获取sign
+        timestamp = int(time.time())
+        current_milli_time = lambda: int(round(time.time() * 1000))
+        data_1 = "appid=%s&iccid=%s&timestamp=%s%s"%("102420177762",iccid,current_milli_time(),"6397d7e6a56589f1d93284e9800493e1")
+        sign = hashlib.sha256(data_1.encode('utf-8')).hexdigest()
+        data = {"appid": "102420177762", "iccid": iccid, "timestamp":current_milli_time(),"sign":sign}
+        url  = "https://api.simboss.com/2.0/device/detail"    
         try:
-            response = requests.request("POST", url, data={"iccid":iccid})
+            status = 1
+            ret = requests.post(url, data=data)
+            code = json.loads(ret.text)["code"]
+            if code == "0":
+                status = 1
+            else:
+                url = 'http://sim.brlink.cn/api/open/iotcard/card'
+                appkey = "iaO2DKgS8KdlnVgU"
+                appsecret = "qzKgO4sBdzMrjRwv9H22S9ufepNv8Hl5ehPqkYVD31DCICjyKwqUdj7zihQQKfgx"
+                status = 2
+                ret = requests.post(url,json={'iccid':iccid},auth=HTTPBasicAuth(appkey,appsecret),timeout=(5,10))
+                codes = json.loads(ret.text)["code"]
+                if codes == 0:
+                    status = 2
+                else:
+                    url = "https://jsnl.xmnengjia.com/open/api/module/cards"
+                    data = {"iccids":[iccid]}
+                    data = json.dumps(data)
+                    ret = requests.post(url,data=data,timeout=(10,30))
+                    print(ret.text)
+                    status = 3
         except:
-            return [0,"查询卡信息异常稍后重试"]
-        else:
-            res_data = json.loads(response.text)
-            if res_data["msg"]=="success" and res_data["data"]:
-                expiry_date = res_data["data"]["expiry_date"]
-                if expiry_date == "未知":
-                    return [0,"未查询到卡信息"]
-                elif expiry_date == "未激活":
-                    return [3, "未激活"]
+            status = 0
+            ret = 0
+        day = 0
+        if ret:
+            try:
+                result = json.loads(ret.text)
+                expiry_date = result.get("data", {}).get("expiry_date")
+                now_date = int(time.time())
+                time_difference = int((expiry_date - now_date) / 3600 / 24) 
+                print(time_difference)
+                if time_difference < 30:
+                    return [0,"有效期剩余{}天".format(time_difference)]
+                elif time_difference >= 181:
+                    return [1,"有效期剩余{}天".format(time_difference)]
                 else:
-                    time_difference = self.__time_dif(expiry_date)
-                    if time_difference < 30:
-                        return [0,"有效期剩余{}天".format(time_difference)]
-                    elif time_difference >= 181:
-                        return [1,"有效期剩余{}天".format(time_difference)]
-                    else:
-                        return [2,"有效期剩余{}天".format(time_difference)]
-            else:
-                return [0,"查询无结果"]
+                    return [2,"有效期剩余{}天".format(time_difference)]
+            except:
+                return [0, "查询无结果"]
+        else:
+            return [0, "查询无结果"]
+
     
     def __bigdata_verify(self,data_cursor,proess):
         ds_verify,ct_verify,cv_verify,bv_verify,rps_verify = [1,"合格"],[0,"无电击数据"],[0,"不存在充电状态"],[1,"合格"],[0,"无雨控数据"]
         tt_verify,stm8vs_verify,dver_verify,lng_verify,lat_verify = [1,"合格"],[1,self.set_stm8vs],[1,self.set_dver],[1,"合格"],[1,"合格"]
         ws_list,ws_count = [],0
         iccid = ""
+        # 经纬度展示不合格条数
+        lng_lst = []
+        lat_lst = []
         for index,i in enumerate(data_cursor):
             addtime = i["addtime"]
             data_strftime = datetime.datetime.fromtimestamp(addtime).strftime("%Y-%m-%d %H:%M:%S")
@@ -526,12 +556,19 @@ class SCDThread(QtCore.QThread):
             if device_data.get("dver","0") != self.set_dver:
                 dver_verify[0],dver_verify[1] = 0, device_data.get("dver","0")
             
-            if float(device_data.get("lng","0")) < 113.7536111 and float(device_data.get("lng","0")) > 113.7869444:
-                lng_verify[0],lng_verify[1] = 0, data_strftime+"超出范围"
-            
-            if float(device_data.get("lat","0")) < 35.0125 and float(device_data.get("lat","0")) > 35.0458333:
-                lat_verify[0],lat_verify[1] = 0, data_strftime+"超出范围"
-            
+            # if float(device_data.get("lng","0")) < 113.7536111 or float(device_data.get("lng","0")) > 113.7869444:
+            #     lng_verify[0],lng_verify[1] = 0, data_strftime+"超出范围"
+
+            # if float(device_data.get("lat","0")) < 35.0125 or float(device_data.get("lat","0")) > 35.0458333:
+            #     lat_verify[0],lat_verify[1] = 0, data_strftime+"超出范围"
+            try:
+                lng_lst.append(float(device_data.get("lng")))
+            except Exception as e:
+                lng_lst.append(0)
+            try:
+                lat_lst.append(float(device_data.get("lat")))
+            except Exception as e:
+                lat_lst.append(0)
             prosee = proess + ((index+1)/data_cursor.count()*(1/len(self.device_list))*100)
             if int(prosee) == 100:
                 self.proess_signal.emit(99)
@@ -558,9 +595,23 @@ class SCDThread(QtCore.QThread):
         else:
             ws_verify=[0,"缺少待机状态"]
         if iccid:
+            print("iccid", iccid)
             sim_verify = self.sim_info(iccid)
         else:
             sim_verify = [0,"数据内无iccid"]
+        # 经纬度处理
+        lg = 0
+        lt = 0
+        for i in lng_lst:
+            if i < 113.7536111 or i > 113.7869444:
+                lg += 1
+        for k in lat_lst:
+            if k < 35.0125 or k > 35.0458333:
+                lt += 1
+        if lg != 0:
+            lng_verify = [0, f"{str(min(lng_lst))}~{str(max(lng_lst))},不合格条数{str(lg)}"]
+        if lt != 0:
+            lat_verify = [0, f"{str(min(lat_lst))}~{str(max(lat_lst))},不合格条数{str(lt)}"]
         return [ds_verify,ws_verify,ct_verify,cv_verify,bv_verify,rps_verify,tt_verify,stm8vs_verify,sim_verify,dver_verify,lng_verify,lat_verify]
 
     def __siqing_verify(self,data_result,status_result,proess):

BIN
temp/~$1_0707测报灯检验-1688710033.xlsx


BIN
temp/~$1_0707测报灯检验-1688713635.xlsx


+ 169 - 0
tools/image_score.py

@@ -0,0 +1,169 @@
+from fileinput import filename
+import numpy as np
+import cv2
+# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
+"""
+Run a Flask REST API exposing one or more YOLOv5s models
+"""
+import requests
+import argparse
+import io
+
+# import torch
+from PIL import Image
+from skimage import filters
+import os
+RESULT_FOLDER = './output_dir/nocutimg' #用于存放检测结果
+
+
+def draw(img,result,dstDir,filenameList,a):
+    """
+    为待检测图片 绘制矩形框和结果分数
+         Args:
+            img (list):利用opesncv按照字节读取的图片
+            result (list):检测结果的分数列表
+            dstDir (str):检测结果存放位置(./output_dir/nocutimg/exp_1/xxx.jpg)
+            filenameList (list):图片名
+            a:圆盘内接四边形坐标 (左上角,右上角)
+
+         return:
+    """
+    try:
+         os.makedirs(dstDir)
+    except:
+         pass
+    for i in range(len(filenameList)):
+        filename = os.path.join(dstDir,filenameList[i])
+        cv2.rectangle(img[i], (a[0], a[1]), (a[2], a[3]), (0, 0, 255), 2)
+        cv2.putText(img[i],"score:{}".format(result[i]), (30, 100),cv2.FONT_HERSHEY_PLAIN,7,(0,0,255),2)
+        cv2.imwrite(filename,img[i])
+    print("检查后图片已存入{}".format(dstDir))
+
+def _imageToMatrix(image):
+        """
+        根据名称读取图片对象转化矩阵
+        :param strName:
+        :return: 返回矩阵
+        """
+        imgMat = np.matrix(image)
+        return imgMat
+
+def preImgOps(img):
+        """
+        图像的预处理操作
+        :param img: 图像的而明朝
+        :return: 灰度化和resize之后的图片对象
+        """
+        # 预处理操作
+        reImg = cv2.resize(img, (300, 400), interpolation=cv2.INTER_CUBIC)  #
+        img2gray = cv2.cvtColor(reImg, cv2.COLOR_BGR2GRAY)  # 将图片压缩为单通道的灰度图
+        return reImg,img2gray
+
+def ReadImage(im_file):
+    """
+        读取图片
+        :param im_file: 图像的路径
+        :return: 利用opencv读取的完整图像img  托虫板内接四边形图像cutimg   内接四边形的坐标c[xmin,ymin,xmax,ymax] 
+    """
+    img = cv2.imdecode(np.fromfile(im_file, dtype=np.uint8), cv2.IMREAD_COLOR)
+    # imgfile = np.asarray(bytearray(im_file.read()), dtype="uint8")
+    # img = cv2.imdecode(imgfile, cv2.IMREAD_ANYCOLOR)
+    ImgShape = img.shape
+    print("原始图像大小{}".format(ImgShape))
+    center = [ImgShape[1]/2,ImgShape[0]/2] #圆盘中心
+    print("图像中心位置{}".format(center))
+    radius = int(ImgShape[0]/2) #圆盘半径
+    print("半径{}".format(radius))
+    length = pow(2,0.5)*radius    #圆的内接正方形边长
+    # print(length)
+    Size = int(length/2)
+    xmin = int(center[0] - Size)
+    xmax = int(center[0] + Size)
+    ymin = int((center[1] - Size)*1.1)
+    ymax = int(center[1] + Size)
+    c = [xmin,ymin,xmax,ymax]
+    # print(c)
+    cutimg = img[ymin:ymax,xmin:xmax]
+    # img = cv2.imdecode(imgfile, cv2.IMREAD_ANYCOLOR)
+    return img,cutimg,c
+
+def getFileName(imageFile):
+    url, FileName = os.path.split(imageFile)
+    # print(FileName)
+    tamp = []
+    tamp.append(FileName)
+    return tamp
+
+#图像清晰度检测
+def predict(imageFile):
+    """
+    图像清晰度检测
+    Args:
+        imageFile(dir or file):单张图片或者存放图片的文件夹
+    """
+    if not os.path.exists(RESULT_FOLDER):
+         os.makedirs(RESULT_FOLDER)
+    else:
+        pass
+    dirs = os.listdir(RESULT_FOLDER)
+    print(dirs)
+    print(imageFile)
+    # return str(len(dirs))
+    result = [] #存放清晰度评分
+    imgList = [] #存放识别后图片
+    if os.path.isdir(imageFile):
+        imageFileList = [os.path.join(imageFile,x) for x in os.listdir(imageFile)]
+        print("imageFileList",imageFileList)
+        for image in imageFileList:
+            print(image)
+            img,cutimg,c = ReadImage(image)
+            reImg, img2gray= preImgOps(cutimg)
+            f = _imageToMatrix(img2gray)
+
+            tmp = filters.sobel(f)
+            source=np.sum(tmp**2)
+            source=np.sqrt(source)
+            result.append(source)
+            imgList.append(img)
+        draw(imgList,result,RESULT_FOLDER+'/exp_'+str(len(dirs)+1)+"/", os.listdir(imageFile),c)
+    elif os.path.isfile(imageFile):
+            print("输入文件")
+            img,cutimg,c = ReadImage(imageFile)
+            reImg, img2gray= preImgOps(cutimg)
+            f = _imageToMatrix(img2gray)
+
+            tmp = filters.sobel(f)
+            source=np.sum(tmp**2)
+            source=np.sqrt(source)
+            result.append(source)
+            imgList.append(img)
+    return result
+
+def main(file_name_is):
+    """
+       imageFile 文件夹或者文件 
+    """
+    # imageFile = "D:\\新建文件夹 (4)\\WeChat Files\\wxid_uqzo45cgfn1j12\\FileStorage\\File\\2023-06\\图片清晰度评分\\861551058842071-20230612141803.jpg"
+    # imageFile = "C:\\Users\\31453\\Desktop\\云飞代码\\imageQuiltyAssign-toyang\\predict\\861551054010806-20230512095242.jpg"
+    # imageFile = "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Basics/cbd/861551053998357/2023/6/20/192.168.1.108_01_20230620040214180_ALARM_INPUT.jpg?"
+    # # 把图片下载到本地
+    # local_dir = "org_image"
+    # file_name = imageFile.split("/")[-1]
+    # file_name = file_name.replace("?", "")
+    # os.makedirs(local_dir) if not os.path.exists(local_dir) else None
+    # response = requests.get(imageFile)
+    # with open(os.path.join(local_dir, file_name), 'wb') as f:
+    # with open(file_name_is, 'wb') as f:
+    #     f.write(response.content)
+    # result = predict(os.path.join(local_dir, file_name))
+    # print(result)
+    result = predict(file_name_is)
+    print(result)
+    
+if __name__ == '__main__':
+    """
+    使用说明:
+        修改main()函数中的imageFile:填入待检测图片url or 待检测图片文件夹url
+    """
+    fi = "E:\\项目列表\\大数据平台\\打分图片\\3.jpg"
+    main(fi)

+ 105 - 0
tools/sim_info.py

@@ -0,0 +1,105 @@
+import json
+from aliyunsdkcore.vendored.requests.auth import HTTPBasicAuth
+import requests
+import datetime
+import time
+import hashlib
+
+
+
+def __time_dif(checkdatetime):
+    """计算时间差"""
+    nowdatetime = datetime.datetime.now()
+    checkdatetime = datetime.datetime.strptime(checkdatetime, "%Y-%m-%d %H:%M:%S")
+    timedif = checkdatetime - nowdatetime
+    return timedif.days
+
+
+def sim_updata(iccid):
+    # 时间戳 用于获取sign
+    timestamp = int(time.time())
+    current_milli_time = lambda: int(round(time.time() * 1000))
+    data_1 = "appid=%s&iccid=%s&timestamp=%s%s"%("102420177762",iccid,current_milli_time(),"6397d7e6a56589f1d93284e9800493e1")
+    sign = hashlib.sha256(data_1.encode('utf-8')).hexdigest()
+    data = {"appid": "102420177762", "iccid": iccid, "timestamp":current_milli_time(),"sign":sign}
+    url  = "https://api.simboss.com/2.0/device/detail"    
+    try:
+        status = 1
+        ret = requests.post(url, data=data)
+        code = json.loads(ret.text)["code"]
+        if code == "0":
+            status = 1
+        else:
+            url = 'http://sim.brlink.cn/api/open/iotcard/card'
+            appkey = "iaO2DKgS8KdlnVgU"
+            appsecret = "qzKgO4sBdzMrjRwv9H22S9ufepNv8Hl5ehPqkYVD31DCICjyKwqUdj7zihQQKfgx"
+            status = 2
+            ret = requests.post(url,json={'iccid':iccid},auth=HTTPBasicAuth(appkey,appsecret),timeout=(5,10))
+            codes = json.loads(ret.text)["code"]
+            if codes == 0:
+                status = 2
+            else:
+                url = "https://jsnl.xmnengjia.com/open/api/module/cards"
+                data = {"iccids":[iccid]}
+                data = json.dumps(data)
+                ret = requests.post(url,data=data,timeout=(10,30))
+                print(ret.text)
+                status = 3
+    except:
+        status = 0
+        ret = 0
+    day = 0
+    print(ret)
+    if ret:
+        try:
+            result = json.loads(ret.text)
+            expiry_date = result.get("data", {}).get("expiry_date")
+            now_date = int(time.time())
+            time_difference = int((expiry_date - now_date) / 3600 / 24) 
+            print(time_difference)
+            if time_difference < 30:
+                return [0,"有效期剩余{}天".format(time_difference)]
+            elif time_difference >= 181:
+                return [1,"有效期剩余{}天".format(time_difference)]
+            else:
+                return [2,"有效期剩余{}天".format(time_difference)]
+        except:
+            return [0, "查询无结果"]
+    else:
+        return [0, "查询无结果"]
+
+
+
+def sim_info(iccid):
+    """查询卡信息"""
+    url = "http://8.136.98.49:10001/iotcard/platsimview/inquiries/"
+    try:
+        response = requests.request("POST", url, data={"iccid":iccid})
+    except:
+        return [0,"查询卡信息异常稍后重试"]
+    else:
+        res_data = json.loads(response.text)
+        if res_data["msg"]=="success" and res_data["data"]:
+            expiry_date = res_data["data"]["expiry_date"]
+            if expiry_date == "未知":
+                return [0,"未查询到卡信息"]
+            elif expiry_date == "未激活":
+                return [3, "未激活"]
+            else:
+                time_difference = __time_dif(expiry_date)
+                if time_difference < 30:
+                    return [0,"有效期剩余{}天".format(time_difference)]
+                elif time_difference >= 181:
+                    return [1,"有效期剩余{}天".format(time_difference)]
+                else:
+                    return [2,"有效期剩余{}天".format(time_difference)]
+        else:
+            return [0,"查询无结果"]
+
+
+if __name__ == "__main__":
+    # result = sim_info("89860480192280587662")
+    
+    # result = sim_updata("89860480192280587662")
+    result = sim_updata("89860492192090432038")
+    print(result)