Spaces:
Sleeping
Sleeping
File size: 3,168 Bytes
9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 557d0ab 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 9e2128d 0caca7a 87e6a62 0caca7a |
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 |
import streamlit as st
import io
import PyPDF2
from google import genai
from google.genai import types
import os
# Sử dụng biến môi trường GOOGLE_API_KEY đã được thiết lập
client = genai.Client()
api_key = os.getenv('GOOGLE_API_KEY')
if not api_key:
st.error("Biến môi trường GOOGLE_API_KEY chưa được thiết lập!")
else:
st.write("API key đã được cấu hình.")
st.title("Gemini 2.5 Pro Chatbot")
st.write("Chatbot sử dụng Google Gen AI SDK (Gemini Developer API)")
# Nhập nội dung chat từ người dùng
user_text = st.text_input("Nhập nội dung chat:")
# Cho phép upload file với các định dạng: jpg, jpeg, png, mp4, mp3, wav, pdf
uploaded_files = st.file_uploader(
"Tải lên file (hỗ trợ: jpg, jpeg, png, mp4, mp3, wav, pdf):",
type=["jpg", "jpeg", "png", "mp4", "mp3", "wav", "pdf"],
accept_multiple_files=True
)
# Tạo danh sách contents để gửi lên model
contents = []
if user_text:
contents.append(user_text)
if uploaded_files:
for file in uploaded_files:
file_bytes = file.read()
file_ext = file.name.split('.')[-1].lower()
if file_ext == "pdf":
# Trích xuất nội dung văn bản từ PDF
try:
pdf_reader = PyPDF2.PdfReader(io.BytesIO(file_bytes))
pdf_text = ""
for page in pdf_reader.pages:
page_text = page.extract_text()
if page_text:
pdf_text += page_text + "\n"
if pdf_text:
contents.append(pdf_text)
else:
st.warning(f"Không thể trích xuất nội dung từ {file.name}.")
except Exception as e:
st.error(f"Lỗi khi xử lý PDF {file.name}: {e}")
else:
# Xác định mime type cho các file khác
if file_ext in ["jpg", "jpeg"]:
mime_type = "image/jpeg"
elif file_ext == "png":
mime_type = "image/png"
elif file_ext == "mp4":
mime_type = "video/mp4"
elif file_ext == "mp3":
mime_type = "audio/mpeg"
elif file_ext == "wav":
mime_type = "audio/wav"
else:
mime_type = "application/octet-stream"
# Tạo Part từ bytes
part = types.Part.from_bytes(data=file_bytes, mime_type=mime_type)
contents.append(part)
if st.button("Gửi"):
if not contents:
st.warning("Vui lòng nhập nội dung chat hoặc upload file.")
else:
with st.spinner("Đang xử lý yêu cầu..."):
try:
# Gọi API generate_content theo cách mẫu trong tài liệu
response = client.models.generate_content(
model='gemini-2.5-flash-preview-04-17',
contents=contents
)
st.write("**Phản hồi từ Gemini:**")
st.write(response.text)
except Exception as e:
st.error(f"Có lỗi xảy ra: {e}") |