File size: 5,780 Bytes
1ad96dd |
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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
import gradio as gr
import os
import PyPDF2
import google.generativeai as genai
# ตั้งค่า API Key
API_KEY = "AIzaSyDED9cUVryPKz7_zXkdVBL3Agrnb3hC1qk" # 🔒 ใส่ API Key จริงของคุณ
os.environ["GOOGLE_API_KEY"] = API_KEY
genai.configure(api_key=API_KEY)
# สร้าง model
try:
model = genai.GenerativeModel('gemini-1.5-flash')
print("✅ เชื่อมต่อ Gemini API สำเร็จ")
except Exception as e:
print(f"❌ เกิดข้อผิดพลาดในการเชื่อมต่อ API: {e}")
model = None
# ฟังก์ชันอ่าน PDF
def extract_text_from_pdf(pdf_file):
try:
if pdf_file is None:
return ""
pdf_reader = PyPDF2.PdfReader(pdf_file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text
except Exception as e:
return f"เกิดข้อผิดพลาดในการอ่านไฟล์ PDF: {str(e)}"
def extract_text_from_multiple_pdfs(pdf_files):
if not pdf_files:
return ""
combined_text = ""
for i, pdf_file in enumerate(pdf_files):
filename = getattr(pdf_file, 'name', f'ไฟล์ที่ {i+1}')
filename = filename.split('/')[-1]
text = extract_text_from_pdf(pdf_file)
combined_text += f"\n\n=== ไฟล์: {filename} ===\n{text}\n"
return combined_text
def generate_response(prompt, system_prompt=""):
try:
if model is None:
return "❌ ไม่สามารถเชื่อมต่อกับ Gemini API ได้"
full_prompt = f"{system_prompt}\n\n{prompt}" if system_prompt else prompt
response = model.generate_content(full_prompt)
return getattr(response, 'text', "ไม่สามารถสร้างคำตอบได้")
except Exception as e:
return f"เกิดข้อผิดพลาด: {str(e)}"
def chat_with_pdf(pdf_files, question, chat_history):
system_prompt = """
คุณเป็นผู้ช่วยอัจฉริยะของกรมประชาสัมพันธ์ประเทศไทย...
"""
if not pdf_files or all(pdf is None for pdf in pdf_files):
response = "❌ กรุณาอัปโหลดไฟล์ PDF อย่างน้อย 1 ไฟล์ก่อนถามคำถาม"
elif not question.strip():
response = "❌ กรุณาใส่คำถาม"
else:
combined_text = extract_text_from_multiple_pdfs(pdf_files)
prompt = f"""
เอกสารทั้งหมด:
{combined_text}
คำถาม: {question}
"""
response = generate_response(prompt, system_prompt)
chat_history.append([question, response])
return "", chat_history
def general_prd_chat(question, chat_history):
system_prompt = "คุณเป็นผู้ช่วยอัจฉริยะของกรมประชาสัมพันธ์..."
if not question.strip():
response = "❌ กรุณาใส่คำถาม"
else:
response = generate_response(question, system_prompt)
chat_history.append([question, response])
return "", chat_history
def news_activities_chat(question, chat_history):
system_prompt = "คุณเป็นผู้ช่วยอัจฉริยะของกรมประชาสัมพันธ์..."
if not question.strip():
response = "❌ กรุณาใส่คำถาม"
else:
response = generate_response(question, system_prompt)
chat_history.append([question, response])
return "", chat_history
def clear_chat():
return []
def create_interface():
with gr.Blocks(title="Chatbot กรมประชาสัมพันธ์") as app:
with gr.Tab("📄 PDF"):
pdf_files = gr.File(label="📎 PDF", file_types=[".pdf"], file_count="multiple")
pdf_question = gr.Textbox(label="คำถาม", lines=2)
pdf_submit = gr.Button("🔍 ถาม")
pdf_clear = gr.Button("🗑️ ล้าง")
pdf_chatbot = gr.Chatbot(height=500)
pdf_submit.click(chat_with_pdf, [pdf_files, pdf_question, pdf_chatbot], [pdf_question, pdf_chatbot])
pdf_clear.click(clear_chat, outputs=pdf_chatbot)
with gr.Tab("🏛️ ข้อมูลทั่วไป"):
general_question = gr.Textbox(label="คำถาม", lines=3)
general_submit = gr.Button("🔍 ถาม")
general_clear = gr.Button("🗑️ ล้าง")
general_chatbot = gr.Chatbot(height=500)
general_submit.click(general_prd_chat, [general_question, general_chatbot], [general_question, general_chatbot])
general_clear.click(clear_chat, outputs=general_chatbot)
with gr.Tab("📰 ข่าวกิจกรรม"):
news_question = gr.Textbox(label="คำถาม", lines=3)
news_submit = gr.Button("🔍 ถาม")
news_clear = gr.Button("🗑️ ล้าง")
news_chatbot = gr.Chatbot(height=500)
news_submit.click(news_activities_chat, [news_question, news_chatbot], [news_question, news_chatbot])
news_clear.click(clear_chat, outputs=news_chatbot)
return app
if __name__ == "__main__":
app = create_interface()
app.launch(server_name="0.0.0.0", server_port=7860, share=True, debug=True)
|