Brunohdez commited on
Commit
48517c8
·
verified ·
1 Parent(s): a5b0d06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -58
app.py CHANGED
@@ -4,12 +4,26 @@ from google.genai import types
4
  from PyPDF2 import PdfReader
5
  import os
6
 
7
- # Configura tu API Key directamente en el código
8
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
9
 
 
 
 
 
 
 
 
 
 
 
 
10
  # Función para generar respuesta desde la API de Google Gemini
11
- def generate_response(user_input):
12
  try:
 
 
 
13
  client = genai.Client(api_key=GEMINI_API_KEY)
14
 
15
  model = "gemini-2.0-flash-thinking-exp-01-21"
@@ -17,7 +31,7 @@ def generate_response(user_input):
17
  types.Content(
18
  role="user",
19
  parts=[
20
- types.Part.from_text(text=user_input),
21
  ],
22
  ),
23
  ]
@@ -40,66 +54,35 @@ def generate_response(user_input):
40
  except Exception as e:
41
  return f"Se produjo un error: {e}"
42
 
43
- # Función para extraer texto de un archivo PDF
44
- def extract_text_from_pdf(pdf_file):
45
- try:
46
- pdf_reader = PdfReader(pdf_file)
47
- text = ""
48
- for page in pdf_reader.pages:
49
- text += page.extract_text() + "\n"
50
- return text
51
- except Exception as e:
52
- return f"Se produjo un error al leer el PDF: {e}"
53
-
54
  # Aplicación Streamlit
55
- st.title("Gemini LLM App")
56
-
57
- # Selección entre Chat o PDF
58
- option = st.radio("Elige una opción:", ("Hablar con el chat", "Subir y preguntar sobre un PDF"))
59
-
60
- # Opción 1: Hablar con el chat
61
- if option == "Hablar con el chat":
62
- # Entrada del usuario para el chat
63
- user_input = st.text_area("Introduce tu solicitud:", placeholder="Escribe algo aquí...")
64
-
65
- # Botón para enviar la solicitud
66
- if st.button("Obtener Respuesta"):
67
- if user_input.strip():
68
- with st.spinner("Generando respuesta..."):
69
- response = generate_response(user_input)
70
- st.success("¡Respuesta generada!")
71
- st.write(response)
72
- else:
73
- st.error("Por favor, introduce una solicitud para continuar.")
74
 
75
- # Opción 2: Subir y preguntar sobre un PDF
76
- elif option == "Subir y preguntar sobre un PDF":
77
- # Subir archivo PDF
78
- uploaded_file = st.file_uploader("Sube un archivo PDF", type="pdf")
79
 
80
- if uploaded_file is not None:
81
- with st.spinner("Extrayendo texto del PDF..."):
82
- pdf_text = extract_text_from_pdf(uploaded_file)
83
 
84
- if pdf_text:
85
- st.success("Texto extraído del PDF correctamente.")
86
 
87
- # Mostrar una parte del contenido extraído
88
- st.text_area("Contenido del PDF:", pdf_text[:1000], height=200)
89
 
90
- # Entrada de pregunta del usuario sobre el PDF
91
- user_question = st.text_area("Haz una pregunta sobre el contenido del PDF:", placeholder="Escribe tu pregunta aquí...")
92
 
93
- # Botón para enviar la pregunta
94
- if st.button("Obtener Respuesta"):
95
- if user_question.strip():
96
- with st.spinner("Generando respuesta..."):
97
- response = generate_response(pdf_text, user_question)
98
- st.success("¡Respuesta generada!")
99
- st.write(response)
100
- else:
101
- st.error("Por favor, introduce una pregunta para continuar.")
102
- else:
103
- st.error("No se pudo extraer texto del archivo PDF. Por favor, intenta con otro archivo.")
104
  else:
105
- st.info("Por favor, sube un archivo PDF para empezar.")
 
 
 
4
  from PyPDF2 import PdfReader
5
  import os
6
 
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:
13
+ pdf_reader = PdfReader(pdf_file)
14
+ text = ""
15
+ for page in pdf_reader.pages:
16
+ text += page.extract_text() + "\n"
17
+ return text
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 la API de Google Gemini
22
+ def generate_response(context, question):
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"
 
31
  types.Content(
32
  role="user",
33
  parts=[
34
+ types.Part.from_text(text=f"Contexto: {context}\n\nPregunta: {question}"),
35
  ],
36
  ),
37
  ]
 
54
  except Exception as e:
55
  return f"Se produjo un error: {e}"
56
 
 
 
 
 
 
 
 
 
 
 
 
57
  # Aplicación Streamlit
58
+ st.title("Gemini LLM App - Consulta PDFs")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ # Subir archivo PDF
61
+ uploaded_file = st.file_uploader("Sube un archivo PDF", type="pdf")
 
 
62
 
63
+ if uploaded_file is not None:
64
+ with st.spinner("Extrayendo texto del PDF..."):
65
+ pdf_text = extract_text_from_pdf(uploaded_file)
66
 
67
+ if pdf_text:
68
+ st.success("Texto extraído del PDF correctamente.")
69
 
70
+ # Mostrar una parte del contenido extraído
71
+ st.text_area("Contenido del PDF:", pdf_text[:1000], height=200)
72
 
73
+ # Entrada de pregunta del usuario
74
+ user_question = st.text_area("Haz una pregunta sobre el contenido del PDF:", placeholder="Escribe tu pregunta aquí...")
75
 
76
+ # Botón para enviar la pregunta
77
+ if st.button("Obtener Respuesta"):
78
+ if user_question.strip():
79
+ with st.spinner("Generando respuesta..."):
80
+ response = generate_response(pdf_text, user_question)
81
+ st.success("¡Respuesta generada!")
82
+ st.write(response)
83
+ else:
84
+ st.error("Por favor, introduce una pregunta para continuar.")
 
 
85
  else:
86
+ st.error("No se pudo extraer texto del archivo PDF. Por favor, intenta con otro archivo.")
87
+ else:
88
+ st.info("Por favor, sube un archivo PDF para empezar.")