devbernie commited on
Commit
9e2128d
·
verified ·
1 Parent(s): e157052

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import base64
3
+ import io
4
+ import google.genai as genai # Import SDK của google-genai
5
+
6
+ # Cấu hình API key và model cho Gemini
7
+ API_KEY = "AIzaSyAD3PeWI8ie3LNDaMqoIoIf6HyfDT6Bfgs"
8
+ MODEL_ID = "gemini-2.0-pro-exp-02-05"
9
+ genai.configure(api_key=API_KEY)
10
+
11
+ st.title("Gemini 2.0 Pro Chatbot")
12
+ st.write("Chào mừng đến với chatbot Gemini sử dụng google-genai SDK!")
13
+
14
+ # Nhập nội dung chat
15
+ user_prompt = st.text_input("Nhập nội dung chat:")
16
+
17
+ # File uploader hỗ trợ nhiều loại file: hình ảnh, video, audio, PDF
18
+ uploaded_files = st.file_uploader(
19
+ "Tải lên file (hỗ trợ: jpg, jpeg, png, mp4, mp3, wav, pdf):",
20
+ type=["jpg", "jpeg", "png", "mp4", "mp3", "wav", "pdf"],
21
+ accept_multiple_files=True
22
+ )
23
+
24
+ attachments = []
25
+
26
+ if uploaded_files:
27
+ for file in uploaded_files:
28
+ file_name = file.name
29
+ file_ext = file_name.split('.')[-1].lower()
30
+ file_bytes = file.read()
31
+
32
+ # Với file PDF, ta có thể trích xuất nội dung text
33
+ if file_ext == "pdf":
34
+ try:
35
+ import PyPDF2
36
+ pdf_reader = PyPDF2.PdfReader(io.BytesIO(file_bytes))
37
+ pdf_text = ""
38
+ for page in pdf_reader.pages:
39
+ pdf_text += page.extract_text() or ""
40
+ attachments.append({
41
+ "type": "pdf",
42
+ "data": pdf_text
43
+ })
44
+ except Exception as e:
45
+ st.error(f"Lỗi khi đọc PDF {file_name}: {e}")
46
+ else:
47
+ # Các file khác: chuyển sang base64 (giả định API hỗ trợ dạng này)
48
+ encoded_file = base64.b64encode(file_bytes).decode('utf-8')
49
+ if file_ext in ["jpg", "jpeg", "png"]:
50
+ attachments.append({
51
+ "type": "image",
52
+ "data": encoded_file
53
+ })
54
+ elif file_ext == "mp4":
55
+ attachments.append({
56
+ "type": "video",
57
+ "data": encoded_file
58
+ })
59
+ elif file_ext in ["mp3", "wav"]:
60
+ attachments.append({
61
+ "type": "audio",
62
+ "data": encoded_file
63
+ })
64
+
65
+ # Nút gửi yêu cầu
66
+ if st.button("Gửi"):
67
+ if not user_prompt and not attachments:
68
+ st.warning("Vui lòng nhập nội dung chat hoặc upload file.")
69
+ else:
70
+ st.spinner("Đang xử lý yêu cầu ...")
71
+ try:
72
+ # Gọi API của Gemini với prompt và các attachments
73
+ response = genai.chat(
74
+ prompt=user_prompt,
75
+ attachments=attachments, # Nếu không có file, gửi rỗng list
76
+ model=MODEL_ID
77
+ )
78
+ st.write("**Phản hồi từ Gemini:**")
79
+ st.write(response)
80
+ except Exception as ex:
81
+ st.error(f"Có lỗi xảy ra: {ex}")