Spaces:
Sleeping
Sleeping
| 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() | |