- comum.py: ler_json (Origin/JSON/tamanho), gravar_atomico e token (CARINHA_TOKEN ou seguranca.json), substituindo 6 copias nos modulos - eventos.py: hub SSE em /eventos com heartbeat e Last-Event-ID; modulos publicam expressao, telemetria, conversa, reacao, ia, motores - /estado agrega o snapshot inicial; /comando unifica gesto/rosto/cor/reacao - /parar-tudo desliga o PCA9685, para reacoes e trava motores ate /rearmar - braco: lease (ttl_ms) e interpolacao com limite de velocidade no servidor - braco e diagnostico nao disputam o PCA9685 (409 para o segundo dono) - fila limitada (20) com validade de 10 s; POST /face usa prefixo "rosto" - /app/config passa a checar Origin e JSON; versao vem de version.json - figurinhas automaticas do Gemini limitadas a 6 por hora - rosto entende a ordem "calma" enviada pelo E-Stop Token so e exigido quando configurado (docs/SEGURANCA.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
111 lines
6.4 KiB
Python
111 lines
6.4 KiB
Python
"""Cérebro local: decisões reais do Qwen, limitadas a expressões do personagem."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import threading
|
|
import time
|
|
from urllib.request import Request,urlopen
|
|
from comum import gravar_atomico, ler_json
|
|
|
|
GESTOS=('piscar','piscadinha','feliz','surpreso','coracao','olhar_esq','olhar_dir','olhar_baixo')
|
|
EVENTOS=('som','movimento','saudacao','sozinho')
|
|
def validar_intencao(data):
|
|
if not isinstance(data,dict) or set(data)!= {'gesto'} or data['gesto'] not in GESTOS:
|
|
raise ValueError('Intenção fora da lista de expressões')
|
|
return data['gesto']
|
|
|
|
class Cerebro:
|
|
def __init__(self,path,controle,enviar):
|
|
self.path=Path(path);self.controle=controle;self.enviar=enviar
|
|
self.endpoint=os.environ.get('CARINHA_IA_URL','http://127.0.0.1:8101')
|
|
self.executor='S10' if '192.168.1.16' in self.endpoint else 'Orange Pi'
|
|
self.lock=threading.Lock();self.ativo=False;self.pending=None;self.busy=False
|
|
self.conversando=False;self.history=[];self.result=None;self.error='';self.last=0;self.generation=0
|
|
self.publicar=lambda tipo,dados:None
|
|
try:self.ativo=json.loads(self.path.read_text())['ativo'] is True
|
|
except (OSError,ValueError,KeyError,TypeError):pass
|
|
threading.Thread(target=self.loop,daemon=True).start()
|
|
def config(self,ativo):
|
|
if type(ativo) is not bool:raise ValueError('ativo deve ser booleano')
|
|
with self.lock:
|
|
gravar_atomico(self.path,dict(ativo=ativo))
|
|
self.ativo=ativo;self.generation+=1;self.pending=None
|
|
status=self.status();self.publicar('ia',status)
|
|
return status
|
|
def status(self):
|
|
with self.lock:return dict(ativo=self.ativo,ocupado=self.busy,modelo='Qwen3-0.6B Q4_K_M',executor=self.executor,ultima=self.result,erro=self.error)
|
|
def event(self,event):
|
|
if event not in EVENTOS:raise ValueError('Evento desconhecido')
|
|
with self.lock:
|
|
if not self.ativo:raise ValueError('Ative a personalidade primeiro')
|
|
if self.busy or self.pending or self.conversando:raise ValueError('IA processando; aguarde')
|
|
self.pending=event
|
|
return dict(ok=True)
|
|
def decide(self,event):
|
|
payload=dict(model='local',messages=[dict(role='system',content='Você é Carinha, um pequeno robô curioso, gentil e expressivo, inspirado em WALL-E. Escolha uma expressão adequada ao evento. Varie os gestos recentes. Responda somente JSON.'),dict(role='user',content=json.dumps(dict(evento=event,recentes=self.history[-3:]),ensure_ascii=False)+' /no_think')],max_tokens=32,temperature=.7,chat_template_kwargs=dict(enable_thinking=False),response_format=dict(type='json_schema',json_schema=dict(name='intencao',strict=True,schema=dict(type='object',properties=dict(gesto=dict(type='string',enum=list(GESTOS))),required=['gesto'],additionalProperties=False))))
|
|
request=Request(self.endpoint+'/v1/chat/completions',data=json.dumps(payload).encode(),headers={'Content-Type':'application/json'})
|
|
start=time.monotonic()
|
|
with urlopen(request,timeout=90) as response:data=json.load(response)
|
|
content=data['choices'][0]['message']['content']
|
|
gesto=validar_intencao(json.loads(content))
|
|
return dict(evento=event,gesto=gesto,segundos=round(time.monotonic()-start,2),horario=time.time())
|
|
def loop(self):
|
|
while True:
|
|
time.sleep(1)
|
|
with self.lock:
|
|
if not self.ativo or self.conversando:continue
|
|
event=self.pending;self.pending=None;generation=self.generation
|
|
# Só observar sensores enquanto o app está online e acordado.
|
|
with self.controle.lock:
|
|
online=time.monotonic()-self.controle.status_at<5
|
|
state=dict(self.controle.estado)
|
|
if not event and online and not state.get('dormindo') and time.monotonic()-self.last>20:
|
|
if state.get('microfone_ativo') and state.get('microfone',0)>.35:event='som'
|
|
elif state.get('camera_ativa') and state.get('movimento',0)>.05:event='movimento'
|
|
elif time.monotonic()-self.last>60:event='sozinho'
|
|
if not event:continue
|
|
with self.lock:
|
|
if self.conversando:continue
|
|
self.busy=True
|
|
try:
|
|
result=self.decide(event)
|
|
with self.lock:
|
|
if self.ativo and generation==self.generation:
|
|
self.result=result;self.error='';self.history.append(result['gesto']);self.history=self.history[-6:]
|
|
with self.controle.lock:
|
|
if time.monotonic()-self.controle.status_at<5 and not self.controle.estado.get('dormindo'):
|
|
self.enviar(result['gesto'])
|
|
except Exception as e:
|
|
with self.lock:self.error=str(e)[:200]
|
|
finally:
|
|
self.last=time.monotonic()
|
|
with self.lock:self.busy=False
|
|
self.publicar('ia',self.status())
|
|
def rotas(self,h,method):
|
|
route=h.path.split('?',1)[0]
|
|
if route=='/ia/modelo' and method=='GET':
|
|
model=Path('/opt/carinha-ai/models/qwen3-0.6b-q4.gguf')
|
|
if not model.exists():h.enviar(json.dumps(dict(erro='Modelo indisponível')),codigo=404);return True
|
|
h.send_response(200);h.send_header('Content-Type','application/octet-stream');h.send_header('Content-Length',str(model.stat().st_size));h.end_headers()
|
|
try:
|
|
with model.open('rb') as source:
|
|
while True:
|
|
chunk=source.read(65536)
|
|
if not chunk:break
|
|
h.wfile.write(chunk)
|
|
except (BrokenPipeError,ConnectionResetError):pass
|
|
return True
|
|
if route not in ('/ia/status','/ia/config','/ia/evento'):return False
|
|
try:
|
|
if method=='GET' and route=='/ia/status':result=self.status()
|
|
elif method=='POST':
|
|
data=ler_json(h,2048)
|
|
if route=='/ia/config':result=self.config(data.get('ativo'))
|
|
elif route=='/ia/evento':result=self.event(data.get('evento'))
|
|
else:raise ValueError('Rota inválida')
|
|
else:raise ValueError('Método inválido')
|
|
h.enviar(json.dumps(result,ensure_ascii=False))
|
|
except (ValueError,TypeError) as e:h.enviar(json.dumps(dict(erro=str(e))),codigo=400)
|
|
return True
|
|
|