Spaces:
Sleeping
Sleeping
File size: 4,963 Bytes
750ddbb b1a497d eef4676 568c189 88fdffe 06ce862 88fdffe 568c189 9f575c6 568c189 750ddbb 568c189 750ddbb 06ce862 d794b7c 759c572 750ddbb 568c189 88fdffe 568c189 750ddbb 568c189 750ddbb 568c189 750ddbb 568c189 bb4d113 88fdffe 568c189 750ddbb 6447e53 f82d37d 6447e53 f82d37d 6447e53 f82d37d 9ff797a aa9d1fd d6f7e8e bda14d0 750ddbb d6f7e8e 750ddbb bda14d0 750ddbb d6f7e8e bda14d0 750ddbb d6f7e8e 750ddbb d6f7e8e 750ddbb 568c189 d6f7e8e 750ddbb d6f7e8e 88fdffe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
import base64
import streamlit as st
import pandas as pd
import json
from datetime import datetime
from pathlib import Path
import firebase_admin
from firebase_admin import credentials, firestore
import os
from groq import Groq # Certifique-se de que a biblioteca Groq está instalada
# Inicializar o Firebase, se ainda não estiver inicializado
if not firebase_admin._apps:
cred = credentials.Certificate("playbot-f0897-firebase-adminsdk-uay8b-0c87a1f1d0.json") # Substitua pelo caminho correto
firebase_admin.initialize_app(cred)
# Cliente Firestore
db = firestore.client()
# Inicializando o cliente Groq
client = Groq(
api_key=os.getenv("GROQ_API"), # Certifique-se de que a chave da API está configurada corretamente no ambiente
)
llava_model = 'meta-llama/llama-4-scout-17b-16e-instruct'
llama31_model ='meta-llama/llama-4-scout-17b-16e-instruct'
# 2. Função para codificação de imagem
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# 3. Função para converter imagem em texto
def image_to_text(client, model, base64_image, prompt):
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
},
},
],
}
],
model=model
)
return chat_completion.choices[0].message.content
# 4. Função para gerar uma brincadeira
def game_generation(client, image_description, age, support_level, stimulus_type):
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": f"Suggest a safe game for a child of {age} years old, with support level {support_level} and focus on {stimulus_type}. The game should use the object described in the image and should not use objects that are dangerous for children, for example, scissors, knives, toothpicks, electrical wires, any sharp object cannot be used. If the object is not dangerous, describe the game in the form of a step-by-step recipe. Note: Write in Portuguese.",
},
{
"role": "user",
"content": image_description,
}
],
model=llama31_model
)
return chat_completion.choices[0].message.content
# Função para salvar dados no Firebase Firestore
def save_to_firestore(data):
db.collection('usuarios').add(data)
st.success("Obrigado por usar o Playbot.")
# Função principal do app Streamlit
def main():
#st.image("autism.png", width=200)
col1, col2, col3 = st.columns([1, 2, 1]) # ajuste as proporções conforme necessário
with col1:
st.write("")
with col2:
st.image("autism.png", caption="PlayBot", use_column_width=True)
with col3:
st.write("")
st.title("PlayBot - Gerador de Brincadeiras", anchor="center")
st.write("Conheça o PlayBot, um assistente inteligente que gera brincadeiras divertidas e educativas para crianças com TEA a partir de uma imagem de um objeto...")
# Entrada de dados do usuário
idade = st.number_input("Idade da criança:", min_value=1, max_value=16, step=1)
nivel_suporte = st.selectbox("Nível de Suporte", ["Nível 1", "Nível 2", "Nível 3"])
tipo_estimulo = st.selectbox("Tipo de Estimulo", ["Sensorial", "Coordenação motora fina", "Coordenação motora grossa","Raciocínio", "Fala"])
# Carregamento de imagem
uploaded_file = st.file_uploader("Envie uma imagem de algum objeto(s) seguro que você tem disponível (png ou jpg)", type=["png", "jpg"])
if uploaded_file is not None:
# Leitura do arquivo
bytes_data = uploaded_file.read()
base64_image = base64.b64encode(bytes_data).decode('utf-8')
prompt = "Describe this image in detail, including the appearance of the object(s)."
# Chamada para converter imagem em descrição de texto
image_description = image_to_text(client, llava_model, base64_image, prompt)
st.write("\n--- Brincadeira ---")
game_description = game_generation(client, image_description, idade, nivel_suporte, tipo_estimulo)
st.write(game_description)
# Salvando dados no Firebase Firestore
data = {
"Idade": idade,
"Nível de Suporte": nivel_suporte,
"Tipo de Estimulo": tipo_estimulo,
"Descrição da Brincadeira": game_description,
"Timestamp": datetime.now().isoformat()
}
save_to_firestore(data)
# Executar o app
if __name__ == "__main__":
main()
|