Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
4 |
+
from langchain.vectorstores import FAISS
|
5 |
+
from googleapiclient.discovery import build
|
6 |
+
from google.oauth2.service_account import Credentials
|
7 |
+
import pickle
|
8 |
+
import time
|
9 |
+
|
10 |
+
# Initialize embeddings model
|
11 |
+
embeddings = HuggingFaceEmbeddings(
|
12 |
+
model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
13 |
+
)
|
14 |
+
|
15 |
+
def load_or_create_vector_store():
|
16 |
+
"""Load existing vector store or create new one"""
|
17 |
+
if os.path.exists("vector_store.pkl"):
|
18 |
+
with open("vector_store.pkl", "rb") as f:
|
19 |
+
return pickle.load(f)
|
20 |
+
|
21 |
+
# Google Sheets setup
|
22 |
+
SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
|
23 |
+
SPREADSHEET_ID = "13mB_WfOQtOxE1bYO1o-f8aYfh-ooRV1fhOASk9M2DwI"
|
24 |
+
|
25 |
+
# Load credentials from environment
|
26 |
+
gcp_credentials = os.getenv("GCP_CREDENTIALS")
|
27 |
+
if not gcp_credentials:
|
28 |
+
return None
|
29 |
+
|
30 |
+
with open("gcp_credentials.json", "w") as f:
|
31 |
+
f.write(gcp_credentials)
|
32 |
+
|
33 |
+
creds = Credentials.from_service_account_file(
|
34 |
+
"gcp_credentials.json",
|
35 |
+
scopes=SCOPES
|
36 |
+
)
|
37 |
+
service = build("sheets", "v4", credentials=creds)
|
38 |
+
|
39 |
+
# Load all sheets
|
40 |
+
sheets = [
|
41 |
+
"geburtstagsinfos",
|
42 |
+
"oeffnungszeiten",
|
43 |
+
"hallenregeln",
|
44 |
+
"hinweise",
|
45 |
+
"kontakt",
|
46 |
+
"attraktionen"
|
47 |
+
]
|
48 |
+
|
49 |
+
# Prepare documents for embeddings
|
50 |
+
documents = []
|
51 |
+
for sheet_name in sheets:
|
52 |
+
try:
|
53 |
+
result = service.spreadsheets().values().get(
|
54 |
+
spreadsheetId=SPREADSHEET_ID,
|
55 |
+
range=sheet_name
|
56 |
+
).execute()
|
57 |
+
rows = result.get('values', [])[1:] # Skip header
|
58 |
+
|
59 |
+
for row in rows:
|
60 |
+
if len(row) >= 2:
|
61 |
+
doc_text = f"Category: {sheet_name}\nQuestion: {row[0]}\nAnswer: {row[1]}"
|
62 |
+
documents.append(doc_text)
|
63 |
+
except Exception as e:
|
64 |
+
print(f"Error loading {sheet_name}: {e}")
|
65 |
+
|
66 |
+
# Create vector store
|
67 |
+
vector_store = FAISS.from_texts(documents, embeddings)
|
68 |
+
|
69 |
+
# Save for future use
|
70 |
+
with open("vector_store.pkl", "wb") as f:
|
71 |
+
pickle.dump(vector_store, f)
|
72 |
+
|
73 |
+
return vector_store
|
74 |
+
|
75 |
+
# Load or create the vector store
|
76 |
+
vector_store = load_or_create_vector_store()
|
77 |
+
|
78 |
+
def format_response(results):
|
79 |
+
"""Format search results into a nice response"""
|
80 |
+
if not results:
|
81 |
+
return """Ups! 😅 Dazu habe ich leider keine passende Information gefunden.
|
82 |
+
|
83 |
+
Aber ich kenne mich super aus mit:
|
84 |
+
- Unseren Öffnungszeiten ⏰
|
85 |
+
- Den Hallenregeln 📋
|
86 |
+
- Geburtstagsfeiern 🎂
|
87 |
+
- Unseren tollen Attraktionen 🎯
|
88 |
+
- Anfahrt & Kontakt 📍
|
89 |
+
|
90 |
+
Frag mich einfach danach!"""
|
91 |
+
|
92 |
+
best_result = results[0]
|
93 |
+
parts = best_result.page_content.split('\n')
|
94 |
+
category = parts[0].replace('Category: ', '')
|
95 |
+
answer = parts[2].replace('Answer: ', '')
|
96 |
+
|
97 |
+
# Format based on category
|
98 |
+
if 'oeffnungszeiten' in category.lower():
|
99 |
+
return f"Hey! Schau mal, wann Du bei uns vorbeikommen kannst:\n\n{answer}\n\nWir freuen uns auf Dich! 🎉"
|
100 |
+
elif 'hallenregeln' in category.lower():
|
101 |
+
return f"Hey! Damit alle Spaß haben und sicher springen können:\n\n{answer}\n\nDanke, dass Du die Regeln beachtest! 🙌"
|
102 |
+
elif 'kontakt' in category.lower():
|
103 |
+
return f"Cool, dass Du zu uns kommen möchtest!\n\n{answer}\n\nBis bald! 🚀"
|
104 |
+
else:
|
105 |
+
return answer
|
106 |
+
|
107 |
+
def chat(message, history):
|
108 |
+
"""Main chat function"""
|
109 |
+
try:
|
110 |
+
if not message.strip():
|
111 |
+
return "", history
|
112 |
+
|
113 |
+
if not vector_store:
|
114 |
+
return "Entschuldigung, der Service ist gerade nicht verfügbar. Bitte versuche es später noch einmal.", history
|
115 |
+
|
116 |
+
# Search for similar content
|
117 |
+
results = vector_store.similarity_search(message, k=1)
|
118 |
+
response = format_response(results)
|
119 |
+
|
120 |
+
history.append({"role": "user", "content": message})
|
121 |
+
history.append({"role": "assistant", "content": response})
|
122 |
+
|
123 |
+
return "", history
|
124 |
+
|
125 |
+
except Exception as e:
|
126 |
+
print(f"Error in chat: {e}")
|
127 |
+
return "Entschuldigung, es ist ein Fehler aufgetreten. Bitte versuche es später noch einmal.", history
|
128 |
+
|
129 |
+
# Gradio Interface
|
130 |
+
with gr.Blocks(css="""
|
131 |
+
.gradio-container {max-width: 800px !important}
|
132 |
+
.message-wrap {max-width: 800px !important}
|
133 |
+
.message {padding: 15px !important; border-radius: 12px !important; margin: 8px !important}
|
134 |
+
.user-message {background-color: #ff6b00 !important; color: white !important; margin-left: 15% !important}
|
135 |
+
.bot-message {background-color: #f5f5f5 !important; margin-right: 15% !important}
|
136 |
+
.input-row {margin-top: 20px !important}
|
137 |
+
footer {display: none !important}
|
138 |
+
""") as demo:
|
139 |
+
|
140 |
+
chatbot = gr.Chatbot(
|
141 |
+
value=[],
|
142 |
+
elem_id="chatbot",
|
143 |
+
height=500,
|
144 |
+
avatar_images=("🧑", "🤖"),
|
145 |
+
type="messages"
|
146 |
+
)
|
147 |
+
|
148 |
+
msg = gr.Textbox(
|
149 |
+
label="Deine Nachricht",
|
150 |
+
placeholder="Was möchtest Du wissen?",
|
151 |
+
lines=2
|
152 |
+
)
|
153 |
+
submit = gr.Button("Senden", variant="primary")
|
154 |
+
|
155 |
+
msg.submit(chat, [msg, chatbot], [msg, chatbot])
|
156 |
+
submit.click(chat, [msg, chatbot], [msg, chatbot])
|
157 |
+
|
158 |
+
# Example questions
|
159 |
+
gr.Examples(
|
160 |
+
examples=[
|
161 |
+
"Was sind die Öffnungszeiten?",
|
162 |
+
"Wie kann ich einen Kindergeburtstag feiern?",
|
163 |
+
"Welche Regeln gibt es?",
|
164 |
+
"Was kostet ein Kindergeburtstag?",
|
165 |
+
"Wo finde ich euch?"
|
166 |
+
],
|
167 |
+
inputs=msg
|
168 |
+
)
|
169 |
+
|
170 |
+
demo.launch()
|