Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,68 +1,108 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from ctransformers import AutoModelForCausalLM
|
| 3 |
import textwrap
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
)
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
# Formata o prompt para incluir contexto bíblico
|
| 18 |
def format_prompt(question):
|
| 19 |
-
|
| 20 |
Por favor, responda à seguinte pergunta com base nas escrituras bíblicas:
|
| 21 |
|
| 22 |
Pergunta: {question}
|
| 23 |
|
| 24 |
Resposta baseada na Bíblia:"""
|
| 25 |
-
return prompt
|
| 26 |
|
| 27 |
-
# Função principal para gerar resposta
|
| 28 |
def generate_biblical_response(question, model):
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
return formatted_response
|
| 38 |
|
| 39 |
-
# Interface Gradio
|
| 40 |
def create_interface():
|
| 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 |
-
# Inicia o aplicativo
|
| 66 |
if __name__ == "__main__":
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from ctransformers import AutoModelForCausalLM
|
| 3 |
import textwrap
|
| 4 |
+
import os
|
| 5 |
+
import logging
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
|
| 8 |
+
# Configurar logging
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
# Diretório para cache
|
| 13 |
+
CACHE_DIR = os.path.join(os.path.expanduser("~"), ".bible_qa_cache")
|
| 14 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
def load_model(progress=gr.Progress()):
|
| 17 |
+
logger.info("Iniciando carregamento do modelo...")
|
| 18 |
+
progress(0, desc="Iniciando carregamento do modelo")
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 22 |
+
"TheBloke/Llama-2-7B-Chat-GGML",
|
| 23 |
+
model_file="llama-2-7b-chat.ggmlv3.q4_0.bin",
|
| 24 |
+
model_type="llama",
|
| 25 |
+
max_new_tokens=512,
|
| 26 |
+
temperature=0.7,
|
| 27 |
+
context_length=2048,
|
| 28 |
+
cache_dir=CACHE_DIR
|
| 29 |
+
)
|
| 30 |
+
progress(1, desc="Modelo carregado com sucesso!")
|
| 31 |
+
logger.info("Modelo carregado com sucesso!")
|
| 32 |
+
return model
|
| 33 |
+
except Exception as e:
|
| 34 |
+
logger.error(f"Erro ao carregar o modelo: {str(e)}")
|
| 35 |
+
raise
|
| 36 |
|
|
|
|
| 37 |
def format_prompt(question):
|
| 38 |
+
return f"""Você é um assistente especializado em conhecimento bíblico.
|
| 39 |
Por favor, responda à seguinte pergunta com base nas escrituras bíblicas:
|
| 40 |
|
| 41 |
Pergunta: {question}
|
| 42 |
|
| 43 |
Resposta baseada na Bíblia:"""
|
|
|
|
| 44 |
|
|
|
|
| 45 |
def generate_biblical_response(question, model):
|
| 46 |
+
try:
|
| 47 |
+
prompt = format_prompt(question)
|
| 48 |
+
response = model(prompt, max_new_tokens=512)
|
| 49 |
+
return textwrap.fill(response, width=80)
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.error(f"Erro ao gerar resposta: {str(e)}")
|
| 52 |
+
return f"Erro ao gerar resposta: {str(e)}"
|
|
|
|
|
|
|
| 53 |
|
|
|
|
| 54 |
def create_interface():
|
| 55 |
+
with gr.Blocks() as demo:
|
| 56 |
+
gr.Markdown("""# Consultor Bíblico Virtual
|
| 57 |
+
Faça perguntas sobre a Bíblia e receba respostas baseadas nas escrituras.""")
|
| 58 |
+
|
| 59 |
+
# Carrega o modelo uma única vez
|
| 60 |
+
model = load_model()
|
| 61 |
+
|
| 62 |
+
with gr.Row():
|
| 63 |
+
with gr.Column():
|
| 64 |
+
question_input = gr.Textbox(
|
| 65 |
+
lines=2,
|
| 66 |
+
placeholder="Digite sua pergunta sobre a Bíblia aqui...",
|
| 67 |
+
label="Sua Pergunta"
|
| 68 |
+
)
|
| 69 |
+
submit_btn = gr.Button("Enviar Pergunta")
|
| 70 |
+
|
| 71 |
+
with gr.Column():
|
| 72 |
+
answer_output = gr.Textbox(
|
| 73 |
+
lines=10,
|
| 74 |
+
label="Resposta"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Exemplos sem cache
|
| 78 |
+
gr.Examples(
|
| 79 |
+
examples=[
|
| 80 |
+
"O que a Bíblia diz sobre amor ao próximo?",
|
| 81 |
+
"Como é descrita a criação do mundo no livro de Gênesis?",
|
| 82 |
+
"Quais são os principais ensinamentos de Jesus sobre perdão?"
|
| 83 |
+
],
|
| 84 |
+
inputs=question_input,
|
| 85 |
+
cache_examples=False # Desativa o cache dos exemplos
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def process_question(question):
|
| 89 |
+
logger.info(f"Processando pergunta: {question}")
|
| 90 |
+
return generate_biblical_response(question, model)
|
| 91 |
+
|
| 92 |
+
submit_btn.click(
|
| 93 |
+
fn=process_question,
|
| 94 |
+
inputs=question_input,
|
| 95 |
+
outputs=answer_output
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
return demo
|
| 99 |
|
|
|
|
| 100 |
if __name__ == "__main__":
|
| 101 |
+
logger.info("Iniciando aplicação...")
|
| 102 |
+
demo = create_interface()
|
| 103 |
+
demo.queue(concurrency_count=1).launch(
|
| 104 |
+
server_name="0.0.0.0",
|
| 105 |
+
share=True,
|
| 106 |
+
show_error=True,
|
| 107 |
+
cache_examples=False
|
| 108 |
+
)
|