Update app.py
Browse files
app.py
CHANGED
|
@@ -7,6 +7,11 @@ import os
|
|
| 7 |
# Leer API Key desde variable de entorno
|
| 8 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# Función para extraer texto de un archivo PDF
|
| 11 |
def extract_text_from_pdf(pdf_file):
|
| 12 |
try:
|
|
@@ -18,71 +23,100 @@ def extract_text_from_pdf(pdf_file):
|
|
| 18 |
except Exception as e:
|
| 19 |
return f"Se produjo un error al leer el PDF: {e}"
|
| 20 |
|
| 21 |
-
# Función para generar respuesta desde
|
| 22 |
-
def
|
| 23 |
try:
|
| 24 |
-
if not GEMINI_API_KEY:
|
| 25 |
-
return "❌ No se encontró la API Key. Asegúrate de configurarla como secreto en Hugging Face."
|
| 26 |
-
|
| 27 |
client = genai.Client(api_key=GEMINI_API_KEY)
|
| 28 |
-
|
| 29 |
-
model = "gemini-2.0-flash-thinking-exp-01-21"
|
| 30 |
contents = [
|
| 31 |
types.Content(
|
| 32 |
role="user",
|
| 33 |
-
parts=[
|
| 34 |
-
|
| 35 |
-
],
|
| 36 |
-
),
|
| 37 |
]
|
| 38 |
-
|
| 39 |
temperature=0.7,
|
| 40 |
top_p=0.95,
|
| 41 |
top_k=64,
|
| 42 |
max_output_tokens=65536,
|
| 43 |
response_mime_type="text/plain",
|
| 44 |
)
|
| 45 |
-
|
| 46 |
response_text = ""
|
| 47 |
for chunk in client.models.generate_content_stream(
|
| 48 |
-
model=
|
| 49 |
contents=contents,
|
| 50 |
-
config=
|
| 51 |
):
|
| 52 |
response_text += chunk.text
|
| 53 |
return response_text
|
| 54 |
except Exception as e:
|
| 55 |
return f"Se produjo un error: {e}"
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
pdf_text = extract_text_from_pdf(uploaded_file)
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
else:
|
| 86 |
-
st.
|
| 87 |
-
else:
|
| 88 |
-
st.info("Por favor, sube un archivo PDF para empezar.")
|
|
|
|
| 7 |
# Leer API Key desde variable de entorno
|
| 8 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 9 |
|
| 10 |
+
# Verificar si la API Key existe
|
| 11 |
+
if not GEMINI_API_KEY:
|
| 12 |
+
st.error("❌ No se encontró la API Key. Agrega 'GEMINI_API_KEY' como secreto en Hugging Face.")
|
| 13 |
+
st.stop()
|
| 14 |
+
|
| 15 |
# Función para extraer texto de un archivo PDF
|
| 16 |
def extract_text_from_pdf(pdf_file):
|
| 17 |
try:
|
|
|
|
| 23 |
except Exception as e:
|
| 24 |
return f"Se produjo un error al leer el PDF: {e}"
|
| 25 |
|
| 26 |
+
# Función para generar respuesta desde Gemini con entrada directa
|
| 27 |
+
def generate_chat_response(user_input):
|
| 28 |
try:
|
|
|
|
|
|
|
|
|
|
| 29 |
client = genai.Client(api_key=GEMINI_API_KEY)
|
|
|
|
|
|
|
| 30 |
contents = [
|
| 31 |
types.Content(
|
| 32 |
role="user",
|
| 33 |
+
parts=[types.Part.from_text(text=user_input)],
|
| 34 |
+
)
|
|
|
|
|
|
|
| 35 |
]
|
| 36 |
+
config = types.GenerateContentConfig(
|
| 37 |
temperature=0.7,
|
| 38 |
top_p=0.95,
|
| 39 |
top_k=64,
|
| 40 |
max_output_tokens=65536,
|
| 41 |
response_mime_type="text/plain",
|
| 42 |
)
|
|
|
|
| 43 |
response_text = ""
|
| 44 |
for chunk in client.models.generate_content_stream(
|
| 45 |
+
model="gemini-2.0-flash-thinking-exp-01-21",
|
| 46 |
contents=contents,
|
| 47 |
+
config=config,
|
| 48 |
):
|
| 49 |
response_text += chunk.text
|
| 50 |
return response_text
|
| 51 |
except Exception as e:
|
| 52 |
return f"Se produjo un error: {e}"
|
| 53 |
|
| 54 |
+
# Función para generar respuesta basada en contexto y pregunta (PDF)
|
| 55 |
+
def generate_pdf_response(context, question):
|
| 56 |
+
try:
|
| 57 |
+
client = genai.Client(api_key=GEMINI_API_KEY)
|
| 58 |
+
contents = [
|
| 59 |
+
types.Content(
|
| 60 |
+
role="user",
|
| 61 |
+
parts=[types.Part.from_text(text=f"Contexto: {context}\n\nPregunta: {question}")],
|
| 62 |
+
)
|
| 63 |
+
]
|
| 64 |
+
config = types.GenerateContentConfig(
|
| 65 |
+
temperature=0.7,
|
| 66 |
+
top_p=0.95,
|
| 67 |
+
top_k=64,
|
| 68 |
+
max_output_tokens=65536,
|
| 69 |
+
response_mime_type="text/plain",
|
| 70 |
+
)
|
| 71 |
+
response_text = ""
|
| 72 |
+
for chunk in client.models.generate_content_stream(
|
| 73 |
+
model="gemini-2.0-flash-thinking-exp-01-21",
|
| 74 |
+
contents=contents,
|
| 75 |
+
config=config,
|
| 76 |
+
):
|
| 77 |
+
response_text += chunk.text
|
| 78 |
+
return response_text
|
| 79 |
+
except Exception as e:
|
| 80 |
+
return f"Se produjo un error: {e}"
|
| 81 |
|
| 82 |
+
# Interfaz de usuario
|
| 83 |
+
st.title("🧠 Gemini LLM App")
|
|
|
|
| 84 |
|
| 85 |
+
# Selección de modo
|
| 86 |
+
option = st.radio("¿Qué deseas hacer?", ("💬 Hablar con el chat", "📄 Subir y preguntar sobre un PDF"))
|
| 87 |
|
| 88 |
+
# 💬 Chat directo
|
| 89 |
+
if option == "💬 Hablar con el chat":
|
| 90 |
+
user_input = st.text_area("Introduce tu mensaje:", placeholder="Escribe algo aquí...")
|
| 91 |
+
if st.button("Obtener Respuesta"):
|
| 92 |
+
if user_input.strip():
|
| 93 |
+
with st.spinner("Pensando..."):
|
| 94 |
+
response = generate_chat_response(user_input)
|
| 95 |
+
st.success("¡Respuesta generada!")
|
| 96 |
+
st.write(response)
|
| 97 |
+
else:
|
| 98 |
+
st.error("Por favor, escribe algo antes de enviar.")
|
| 99 |
|
| 100 |
+
# 📄 Consulta de PDF
|
| 101 |
+
elif option == "📄 Subir y preguntar sobre un PDF":
|
| 102 |
+
uploaded_file = st.file_uploader("Sube un archivo PDF", type="pdf")
|
| 103 |
+
if uploaded_file:
|
| 104 |
+
with st.spinner("Extrayendo texto del PDF..."):
|
| 105 |
+
pdf_text = extract_text_from_pdf(uploaded_file)
|
| 106 |
|
| 107 |
+
if pdf_text:
|
| 108 |
+
st.success("Texto extraído correctamente.")
|
| 109 |
+
st.text_area("Contenido del PDF (vista previa):", pdf_text[:1000], height=200)
|
| 110 |
+
user_question = st.text_area("Haz una pregunta sobre el contenido del PDF:", placeholder="Ej. ¿De qué trata este documento?")
|
| 111 |
+
if st.button("Obtener Respuesta"):
|
| 112 |
+
if user_question.strip():
|
| 113 |
+
with st.spinner("Generando respuesta..."):
|
| 114 |
+
response = generate_pdf_response(pdf_text, user_question)
|
| 115 |
+
st.success("¡Respuesta generada!")
|
| 116 |
+
st.write(response)
|
| 117 |
+
else:
|
| 118 |
+
st.error("Escribe una pregunta para continuar.")
|
| 119 |
+
else:
|
| 120 |
+
st.error("No se pudo extraer texto. Intenta con otro archivo.")
|
| 121 |
else:
|
| 122 |
+
st.info("Por favor, sube un archivo PDF.")
|
|
|
|
|
|