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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import PyPDF2
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
|
| 6 |
+
# ตั้งค่า API Key
|
| 7 |
+
API_KEY = "AIzaSyDED9cUVryPKz7_zXkdVBL3Agrnb3hC1qk" # 🔒 ใส่ API Key จริงของคุณ
|
| 8 |
+
os.environ["GOOGLE_API_KEY"] = API_KEY
|
| 9 |
+
genai.configure(api_key=API_KEY)
|
| 10 |
+
|
| 11 |
+
# สร้าง model
|
| 12 |
+
try:
|
| 13 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 14 |
+
print("✅ เชื่อมต่อ Gemini API สำเร็จ")
|
| 15 |
+
except Exception as e:
|
| 16 |
+
print(f"❌ เกิดข้อผิดพลาดในการเชื่อมต่อ API: {e}")
|
| 17 |
+
model = None
|
| 18 |
+
|
| 19 |
+
# ฟังก์ชันอ่าน PDF
|
| 20 |
+
def extract_text_from_pdf(pdf_file):
|
| 21 |
+
try:
|
| 22 |
+
if pdf_file is None:
|
| 23 |
+
return ""
|
| 24 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
| 25 |
+
text = ""
|
| 26 |
+
for page in pdf_reader.pages:
|
| 27 |
+
text += page.extract_text() + "\n"
|
| 28 |
+
return text
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"เกิดข้อผิดพลาดในการอ่านไฟล์ PDF: {str(e)}"
|
| 31 |
+
|
| 32 |
+
def extract_text_from_multiple_pdfs(pdf_files):
|
| 33 |
+
if not pdf_files:
|
| 34 |
+
return ""
|
| 35 |
+
combined_text = ""
|
| 36 |
+
for i, pdf_file in enumerate(pdf_files):
|
| 37 |
+
filename = getattr(pdf_file, 'name', f'ไฟล์ที่ {i+1}')
|
| 38 |
+
filename = filename.split('/')[-1]
|
| 39 |
+
text = extract_text_from_pdf(pdf_file)
|
| 40 |
+
combined_text += f"\n\n=== ไฟล์: {filename} ===\n{text}\n"
|
| 41 |
+
return combined_text
|
| 42 |
+
|
| 43 |
+
def generate_response(prompt, system_prompt=""):
|
| 44 |
+
try:
|
| 45 |
+
if model is None:
|
| 46 |
+
return "❌ ไม่สามารถเชื่อมต่อกับ Gemini API ได้"
|
| 47 |
+
full_prompt = f"{system_prompt}\n\n{prompt}" if system_prompt else prompt
|
| 48 |
+
response = model.generate_content(full_prompt)
|
| 49 |
+
return getattr(response, 'text', "ไม่สามารถสร้างคำตอบได้")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
return f"เกิดข้อผิดพลาด: {str(e)}"
|
| 52 |
+
|
| 53 |
+
def chat_with_pdf(pdf_files, question, chat_history):
|
| 54 |
+
system_prompt = """
|
| 55 |
+
คุณเป็นผู้ช่วยอัจฉริยะของกรมประชาสัมพันธ์ประเทศไทย...
|
| 56 |
+
"""
|
| 57 |
+
if not pdf_files or all(pdf is None for pdf in pdf_files):
|
| 58 |
+
response = "❌ กรุณาอัปโหลดไฟล์ PDF อย่างน้อย 1 ไฟล์ก่อนถามคำถาม"
|
| 59 |
+
elif not question.strip():
|
| 60 |
+
response = "❌ กรุณาใส่คำถาม"
|
| 61 |
+
else:
|
| 62 |
+
combined_text = extract_text_from_multiple_pdfs(pdf_files)
|
| 63 |
+
prompt = f"""
|
| 64 |
+
เอกสารทั้งหมด:
|
| 65 |
+
{combined_text}
|
| 66 |
+
|
| 67 |
+
คำถาม: {question}
|
| 68 |
+
"""
|
| 69 |
+
response = generate_response(prompt, system_prompt)
|
| 70 |
+
chat_history.append([question, response])
|
| 71 |
+
return "", chat_history
|
| 72 |
+
|
| 73 |
+
def general_prd_chat(question, chat_history):
|
| 74 |
+
system_prompt = "คุณเป็นผู้ช่วยอัจฉริยะของกรมประชาสัมพันธ์..."
|
| 75 |
+
if not question.strip():
|
| 76 |
+
response = "❌ กรุณาใส่คำถาม"
|
| 77 |
+
else:
|
| 78 |
+
response = generate_response(question, system_prompt)
|
| 79 |
+
chat_history.append([question, response])
|
| 80 |
+
return "", chat_history
|
| 81 |
+
|
| 82 |
+
def news_activities_chat(question, chat_history):
|
| 83 |
+
system_prompt = "คุณเป็นผู้ช่วยอัจฉริยะของกรมประชาสัมพันธ์..."
|
| 84 |
+
if not question.strip():
|
| 85 |
+
response = "❌ กรุณาใส่คำถาม"
|
| 86 |
+
else:
|
| 87 |
+
response = generate_response(question, system_prompt)
|
| 88 |
+
chat_history.append([question, response])
|
| 89 |
+
return "", chat_history
|
| 90 |
+
|
| 91 |
+
def clear_chat():
|
| 92 |
+
return []
|
| 93 |
+
|
| 94 |
+
def create_interface():
|
| 95 |
+
with gr.Blocks(title="Chatbot กรมประชาสัมพันธ์") as app:
|
| 96 |
+
with gr.Tab("📄 PDF"):
|
| 97 |
+
pdf_files = gr.File(label="📎 PDF", file_types=[".pdf"], file_count="multiple")
|
| 98 |
+
pdf_question = gr.Textbox(label="คำถาม", lines=2)
|
| 99 |
+
pdf_submit = gr.Button("🔍 ถาม")
|
| 100 |
+
pdf_clear = gr.Button("🗑️ ล้าง")
|
| 101 |
+
pdf_chatbot = gr.Chatbot(height=500)
|
| 102 |
+
|
| 103 |
+
pdf_submit.click(chat_with_pdf, [pdf_files, pdf_question, pdf_chatbot], [pdf_question, pdf_chatbot])
|
| 104 |
+
pdf_clear.click(clear_chat, outputs=pdf_chatbot)
|
| 105 |
+
|
| 106 |
+
with gr.Tab("🏛️ ข้อมูลทั่วไป"):
|
| 107 |
+
general_question = gr.Textbox(label="คำถาม", lines=3)
|
| 108 |
+
general_submit = gr.Button("🔍 ถาม")
|
| 109 |
+
general_clear = gr.Button("🗑️ ล้าง")
|
| 110 |
+
general_chatbot = gr.Chatbot(height=500)
|
| 111 |
+
|
| 112 |
+
general_submit.click(general_prd_chat, [general_question, general_chatbot], [general_question, general_chatbot])
|
| 113 |
+
general_clear.click(clear_chat, outputs=general_chatbot)
|
| 114 |
+
|
| 115 |
+
with gr.Tab("📰 ข่าวกิจกรรม"):
|
| 116 |
+
news_question = gr.Textbox(label="คำถาม", lines=3)
|
| 117 |
+
news_submit = gr.Button("🔍 ถาม")
|
| 118 |
+
news_clear = gr.Button("🗑️ ล้าง")
|
| 119 |
+
news_chatbot = gr.Chatbot(height=500)
|
| 120 |
+
|
| 121 |
+
news_submit.click(news_activities_chat, [news_question, news_chatbot], [news_question, news_chatbot])
|
| 122 |
+
news_clear.click(clear_chat, outputs=news_chatbot)
|
| 123 |
+
|
| 124 |
+
return app
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
app = create_interface()
|
| 128 |
+
app.launch(server_name="0.0.0.0", server_port=7860, share=True, debug=True)
|