tiya1012 commited on
Commit
00edd95
·
verified ·
1 Parent(s): db39c55

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -64
app.py CHANGED
@@ -1,64 +1,128 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)