36_pictureAnalysis.py 11 KB

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