36_pictureAnalysis.py 11 KB

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