36_pictureAnalysis.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. from maix import display
  2. from maix import image
  3. from maix import camera
  4. import pyaudio
  5. import wave
  6. import os
  7. from maix import mjpg
  8. from maix import utils
  9. import base64
  10. import time
  11. import requests
  12. import json
  13. import uuid
  14. import threading
  15. import socket
  16. import uuid
  17. import sys
  18. sys.path.append('/root/')
  19. from CocoPi import BUTTON
  20. import os
  21. ScreenOrientation = False
  22. try:
  23. if os.path.exists("/etc/cameraSize.cfg"):
  24. cameraSize = True
  25. else:
  26. cameraSize = False
  27. except:
  28. cameraSize = False
  29. def getLcdRotation(cameraCapture):
  30. global cameraSize
  31. if cameraSize:
  32. return lcdRotationNew(cameraCapture)
  33. else:
  34. return lcdRotation(cameraCapture)
  35. def lcdRotationNew(inputImg):
  36. global cameraSize,ScreenOrientation
  37. imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
  38. if ScreenOrientation:
  39. imgRotationAim = image.new(size = (240, 320))
  40. rotationAngle = 90
  41. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  42. else:
  43. imgRotationAim = image.new(size = (320, 240))
  44. GETROTATION = imageRotationBuffer
  45. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  46. return GETROTATION
  47. def lcdRotation(inputImg):
  48. global cameraSize,ScreenOrientation
  49. imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
  50. if ScreenOrientation:
  51. imgRotationAim = image.new(size = (240, 320))
  52. rotationAngle = 180
  53. else:
  54. imgRotationAim = image.new(size = (320, 240))
  55. rotationAngle = 90
  56. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  57. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  58. return GETROTATION
  59. key_B = BUTTON(8)
  60. key_C = BUTTON(13)
  61. key_D = BUTTON(7)
  62. if cameraSize==True:
  63. camera.camera.config(size=(320,240))
  64. else:
  65. camera.camera.config(size=(240,320))
  66. image.load_freetype("/root/preset/fonts/simhei.ttf")
  67. canvas = image.new(size = (320, 240))
  68. # 播放
  69. def voice_numberMap(value):
  70. valueScaled = float(value - 0) / float(100)
  71. return int(valueScaled * 31)
  72. VOICESTATE = 0
  73. VOICESTREAM = ""
  74. VOICEPYAUDIO = pyaudio.PyAudio()
  75. CHUNK = 1024
  76. VOICEPLAYSTATE = True
  77. VOICEWF = ""
  78. VOICEPPATH = ""
  79. VOICENUMP = str(voice_numberMap(100))
  80. time.sleep(0.01)
  81. SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\"LINEOUT volume\" "+ VOICENUMP+""
  82. def playVoice():
  83. global VOICEPLAYSTATE
  84. VOICEPLAYSTATE = True
  85. VOICEPLAYSTATE = VoicePlayState()
  86. def VoicePlayState():
  87. global VOICESTATE,VOICEDATA,CHUNK,VOICESTREAM,VOICEPYAUDIO,VOICEWF,VOICEPPATH
  88. if VOICESTATE == 0:
  89. VOICEWF = wave.open(VOICEPPATH, "rb")#(sys.argv[1], "rb"
  90. VOICEPYAUDIO = pyaudio.PyAudio()
  91. VOICESTREAM = VOICEPYAUDIO.open(format=VOICEPYAUDIO.get_format_from_width(VOICEWF.getsampwidth()),channels=VOICEWF.getnchannels(),rate=VOICEWF.getframerate(),output=True)
  92. VOICEDATA = VOICEWF.readframes(CHUNK)
  93. VOICESTATE = 1
  94. return True
  95. else:
  96. if len(VOICEDATA) > 0:
  97. try:
  98. VOICESTREAM.write(VOICEDATA)
  99. VOICEDATA = VOICEWF.readframes(CHUNK)
  100. return True
  101. except:
  102. VOICESTATE = 0
  103. else:
  104. VOICESTREAM.stop_stream()
  105. VOICESTREAM.close()
  106. VOICEPYAUDIO.terminate()
  107. VOICESTATE = 0
  108. return False
  109. # 线程1
  110. def thread_calsss_fun1():
  111. global isStateVoice
  112. while True:
  113. if isStateVoice==1:
  114. getImage()
  115. elif VOICEPPATH != "" and isStateVoice == 3:
  116. playVoice()
  117. # 关闭线程
  118. # CocoPiThread1.join()
  119. # 图片转base64
  120. def encode_image(image_path):
  121. img_data = ""
  122. try:
  123. with open(image_path, "rb") as f:
  124. img_data = f.read()
  125. except:
  126. pass
  127. return str(base64.b64encode(img_data), "utf-8")
  128. def getImage():
  129. global imgUrlStr,isStateVoice,cameraImgUrl,VOICEPPATH
  130. uid = str(uuid.uuid1().hex)
  131. strBase = encode_image(cameraImgUrl)
  132. VOICEPPATH = ""
  133. params = {
  134. "max_tokens": 4096,
  135. "messages":[
  136. {
  137. "role": "user",
  138. "content":[
  139. {"text": "图片讲述了什么?","type": "text"},
  140. {"image_url": {"url": f"data:image/jpeg;base64,{strBase}"},"type": "image_url"}
  141. ]
  142. }
  143. ],
  144. "uid": uid,
  145. "stream": False
  146. }
  147. headers={
  148. "Content-Type":"application/json"
  149. }
  150. res = requests.post("https://gpt4.cocorobo.cn/imageAnalyse", headers=headers, data=json.dumps(params))
  151. try:
  152. if res.status_code == 200:
  153. isStateVoice = 3
  154. aa = json.loads(res.text)["FunctionResponse"]["choices"][0]["message"]["content"]
  155. result_num = len(aa)//20
  156. for i in range(result_num + 1):
  157. imgUrlStr.append("")
  158. imgUrlStr[i] = str(aa)[i*20:(i+1)*20]
  159. url = "https://gpt4.cocorobo.cn/getV831Audio"
  160. payload = json.dumps({"input": aa,"response_format":"mp3","voice": "shimmer","uid":uid})
  161. response=requests.request("POST", url, headers=headers, data=payload)
  162. if response.status_code == 200:
  163. # print(json.loads(response.text)["FunctionResponse"]["url"])
  164. a = "https://gpt4.cocorobo.cn" + json.loads(response.text)["FunctionResponse"]["url"]
  165. r = requests.get(a)
  166. with open("/root/preset/audio/" + uid+".wav","wb") as f:
  167. f.write(r.content)
  168. VOICEPPATH = "/root/preset/audio/" + uid+".wav"
  169. except:
  170. isStateVoice = 3
  171. imgUrlStr = ["Fail"]
  172. pass
  173. # 判断联网
  174. def wifi_is_content():
  175. global getDateNum
  176. cmd = "ifconfig"
  177. res = os.popen(cmd).read()
  178. data = False
  179. if res.rfind("inet addr:")!=48:
  180. data = True
  181. return data
  182. def getPrivateIp():
  183. st = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  184. try:
  185. st.connect(("10.255.255.255",1))
  186. IP = st.getsockname()[0]
  187. except Exception:
  188. IP = "127.0.0.1"
  189. finally:
  190. st.close()
  191. return IP
  192. isStateVoice = 0 # 变量为0开始录音,1 GPT 识别录音结果
  193. ScreenOrientation = False
  194. CAMERAROTATE = +90
  195. ssidInfo = ""
  196. passwordInfo = ""
  197. checkConnectState = False
  198. connectText = ""
  199. startConnect=False
  200. wifiConnectState = False
  201. # PublicIp=""
  202. PrivateIP=""
  203. runConnectSig=True
  204. connectSuccessSig=False
  205. while True:
  206. if wifi_is_content():
  207. break
  208. else:
  209. canvas = getLcdRotation(camera.capture())
  210. if ssidInfo!="" and passwordInfo!="":
  211. startConnect=True
  212. #connectText = "Waitting for Connection..."
  213. #canvas.draw_string(10,40, ssidInfo+" "+str(len(ssidInfo))+" "+str(type(ssidInfo)), scale = 1.5, color = (0,0,0), thickness = 1)
  214. canvas.draw_string(10,50, "WiFi 连接中...", scale = 1.5, color = (0,0,0), thickness = 1)
  215. display.show(canvas)
  216. if startConnect==True:
  217. canvas_1 = image.new(size = (320, 320), color = (255,255,255), mode = "RGB")
  218. canvas.draw_image(canvas_1,0,0, alpha=0.4)
  219. if wifiConnectState == True:
  220. if key_B.is_pressed():
  221. while (key_B.is_pressed() == True):
  222. time.sleep(0.001)
  223. startConnect= False
  224. connectText = ""
  225. checkConnectState = False
  226. connectSuccessSig = False
  227. wifiConnectState = False
  228. runConnectSig== True
  229. ssidInfo=""
  230. passwordInfo=""
  231. if checkConnectState == True:
  232. if connectSuccessSig == False:
  233. # PublicIp=getPublicIp()
  234. connectSuccessSig = True
  235. connectText = "Wifi 连接成功!"
  236. # canvas.draw_string(10,80, "The WLAN PUBLIC IP:" + PublicIp, scale = 1.5, color = (0,0,0), thickness = 1)
  237. canvas.draw_string(10,110, "IP:" + PrivateIP, scale = 1.5, color = (0,0,0), thickness = 1)
  238. # canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
  239. ssidInfo=""
  240. passwordInfo=""
  241. canvas.clear()
  242. break
  243. else:
  244. pass
  245. else:
  246. if checkConnectState == False:
  247. os.system("wifi_disconnect_ap_test")
  248. os.system('wifi_connect_chinese_ap_test '+ssidInfo+' '+passwordInfo+'')
  249. checkConnectState = True
  250. if checkConnectState == True:
  251. if key_B.is_pressed():
  252. while (key_B.is_pressed() == True):
  253. time.sleep(0.001)
  254. startConnect= False
  255. connectText = ""
  256. checkConnectState = False
  257. connectSuccessSig = False
  258. wifiConnectState = False
  259. runConnectSig== True
  260. passwordInfo = ""
  261. ssidInfo = ""
  262. else:
  263. if runConnectSig== True:
  264. connectText = "WIFI 连接中,请等待..."
  265. runConnectSig= False
  266. else:
  267. passwordInfo = ""
  268. ssidInfo = ""
  269. connectText = "Wifi 连接失败!"
  270. canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
  271. canvas.draw_string(10,50, connectText, scale = 1.5, color = (0,0,0) , thickness = 1)
  272. else:
  273. mks = canvas.find_qrcodes()
  274. for mk in mks:
  275. #外框数据
  276. X = mk['x']
  277. Y = mk['y']
  278. W = mk['w']
  279. H = mk['h']
  280. #二维码信息
  281. string = mk['payload']
  282. codeData = string.split(";")
  283. ssidInfo = codeData[0].split(":")[1]
  284. passwordInfo = codeData[1].split(":")[1]
  285. #画外框
  286. canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2)
  287. #打印信息
  288. canvas.draw_string(int(X) , int(Y - 45) , "WIFI 名:"+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2) #内框ID
  289. canvas.draw_string(int(X) , int(Y - 25) , "密码:"+passwordInfo, scale = 1, color = (255, 0, 0), thickness = 2) #内框ID
  290. canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
  291. display.show(canvas)
  292. imgUrlStr = []
  293. # 线程1
  294. CocoPiThread1 = threading.Thread(target=thread_calsss_fun1)
  295. # 开启线程
  296. CocoPiThread1.start()
  297. cameraImgUrl = ""
  298. # getImage()
  299. image_num = 0
  300. while True:
  301. if key_D.is_pressed():
  302. isStateVoice = 0
  303. imgUrlStr = []
  304. VOICEPPATH = ""
  305. if len(imgUrlStr) > 0 and isStateVoice ==3:
  306. canvas.clear()
  307. canvas.draw_image((image.open("/root/preset/img/clockwise_bfbfbf_24x24.png")).rotate(0, adjust=0),2,2,alpha=1)
  308. if len(imgUrlStr) > 0:
  309. for i in range(len(imgUrlStr)):
  310. canvas.draw_string(0,15*(i + 2), str(imgUrlStr[i]), scale = 1, color = (255,255,255) , thickness = 1)
  311. elif isStateVoice != 2 and isStateVoice != 1:
  312. canvas.clear()
  313. canvas = getLcdRotation(camera.capture())
  314. if key_C.is_pressed():
  315. while not (key_C.is_pressed() == False):
  316. time.sleep(0.1)
  317. image_num = image_num + 1
  318. cameraImgUrl = "/root/user/img/image"+str(image_num)+ ".jpg"
  319. save_path = cameraImgUrl
  320. canvas.save(save_path)
  321. display.show(canvas)
  322. time.sleep(1)
  323. imgUrlStr = []
  324. isStateVoice = 1
  325. canvas.draw_image((image.open("/root/preset/img/camera_bfbfbf_24x24.png")).rotate(0, adjust=0),292,2,alpha=1)
  326. display.show(canvas)