SilverWulf212 commited on
Commit
8865699
·
verified ·
1 Parent(s): 3d70b34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +182 -77
app.py CHANGED
@@ -1,78 +1,183 @@
1
- import gradio as gr
2
- import chromadb
3
- from sentence_transformers import SentenceTransformer
4
- import google.generativeai as genai
5
- import os
6
-
7
- # Get API key from Hugging Face secrets
8
- GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
9
- genai.configure(api_key=GOOGLE_API_KEY)
10
-
11
- # Load models (cached)
12
- embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
13
- chroma_client = chromadb.PersistentClient(path="./deadcells_db_free")
14
- collection = chroma_client.get_collection(name="deadcells_wiki")
15
-
16
- # Find Gemini model
17
- available_model = 'gemini-1.5-flash-latest'
18
-
19
- def get_embedding(text):
20
- return embedding_model.encode(text).tolist()
21
-
22
- def chat(message, history):
23
- """Handle chat messages"""
24
-
25
- # Search wiki
26
- question_embedding = get_embedding(message)
27
- results = collection.query(
28
- query_embeddings=[question_embedding],
29
- n_results=5
30
- )
31
-
32
- relevant_chunks = results['documents'][0]
33
- sources = results['metadatas'][0]
34
-
35
- if not relevant_chunks:
36
- return "I couldn't find any relevant information in the wiki."
37
-
38
- # Build context
39
- context = "\n\n---\n\n".join(relevant_chunks)
40
-
41
- # Ask Gemini
42
- model = genai.GenerativeModel(available_model)
43
- prompt = f"""You are a Dead Cells expert. Answer using ONLY the provided wiki content.
44
-
45
- Wiki Content:
46
- {context}
47
-
48
- Question: {message}
49
-
50
- Answer:"""
51
-
52
- response = model.generate_content(prompt)
53
- answer = response.text
54
-
55
- # Add sources
56
- source_list = "\n\n📚 **Sources:** " + ", ".join([s['source'] for s in sources])
57
-
58
- return answer + source_list
59
-
60
- # Create Gradio interface
61
- demo = gr.ChatInterface(
62
- fn=chat,
63
- title="🎮 Dead Cells Wiki Bot",
64
- description="Ask me anything about Dead Cells! I answer using the official wiki.",
65
- examples=[
66
- "What achievements are there for beating bosses?",
67
- "Tell me about the Hand of the King",
68
- "How does malaise work?",
69
- "What are boss stem cells?",
70
- ],
71
- theme="soft",
72
- retry_btn=None,
73
- undo_btn=None,
74
- clear_btn="Clear Chat"
75
- )
76
-
77
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  demo.launch()
 
1
+ import gradio as gr
2
+ import chromadb
3
+ from sentence_transformers import SentenceTransformer
4
+ import google.generativeai as genai
5
+ import os
6
+ import glob
7
+
8
+ # Get API key
9
+ GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
10
+ genai.configure(api_key=GOOGLE_API_KEY)
11
+
12
+ # Load embedding model
13
+ print("Loading embedding model...")
14
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
15
+ print("Model loaded!")
16
+
17
+ # Create or load database
18
+ print("Checking database...")
19
+ chroma_client = chromadb.PersistentClient(path="./deadcells_db_free")
20
+
21
+ try:
22
+ collection = chroma_client.get_collection(name="deadcells_wiki")
23
+ print(f"✅ Database loaded! {collection.count()} chunks available")
24
+
25
+ except Exception as e:
26
+ print(f"Database not found! Building from wiki files...")
27
+
28
+ # Create collection
29
+ collection = chroma_client.create_collection(name="deadcells_wiki")
30
+
31
+ # Load wiki files
32
+ wiki_files = glob.glob("wiki_content/*.txt")
33
+
34
+ if not wiki_files:
35
+ raise Exception(f"❌ No wiki files found! Please upload wiki_content folder")
36
+
37
+ print(f"Found {len(wiki_files)} wiki files. Starting vectorization...")
38
+
39
+ chunk_id = 0
40
+ batch_size = 100
41
+ batch_texts = []
42
+ batch_embeddings = []
43
+ batch_metadatas = []
44
+ batch_ids = []
45
+
46
+ for idx, filepath in enumerate(wiki_files):
47
+ filename = os.path.basename(filepath)
48
+
49
+ try:
50
+ with open(filepath, 'r', encoding='utf-8') as f:
51
+ content = f.read()
52
+
53
+ # Parse file
54
+ lines = content.split('\n')
55
+ url = lines[0].replace('URL: ', '') if lines and lines[0].startswith('URL:') else ''
56
+ text = '\n'.join(lines[2:]) if len(lines) > 2 else content
57
+
58
+ # Skip if empty
59
+ if not text or len(text.strip()) < 100:
60
+ continue
61
+
62
+ # Simple chunking
63
+ words = text.split()
64
+ for i in range(0, len(words), 800):
65
+ chunk = ' '.join(words[i:i + 1000])
66
+
67
+ if len(chunk.split()) < 50:
68
+ continue
69
+
70
+ # Create embedding
71
+ embedding = embedding_model.encode(chunk).tolist()
72
+
73
+ # Add to batch
74
+ batch_texts.append(chunk)
75
+ batch_embeddings.append(embedding)
76
+ batch_metadatas.append({
77
+ "source": filename,
78
+ "url": url,
79
+ "chunk_index": i
80
+ })
81
+ batch_ids.append(f"chunk-{chunk_id}")
82
+ chunk_id += 1
83
+
84
+ # Upload batch when full
85
+ if len(batch_texts) >= batch_size:
86
+ collection.add(
87
+ documents=batch_texts,
88
+ embeddings=batch_embeddings,
89
+ metadatas=batch_metadatas,
90
+ ids=batch_ids
91
+ )
92
+ batch_texts = []
93
+ batch_embeddings = []
94
+ batch_metadatas = []
95
+ batch_ids = []
96
+
97
+ except Exception as file_error:
98
+ print(f"⚠️ Error processing {filename}: {file_error}")
99
+ continue
100
+
101
+ # Progress update
102
+ if (idx + 1) % 50 == 0:
103
+ print(f"Processed {idx + 1}/{len(wiki_files)} files...")
104
+
105
+ # Upload remaining batch
106
+ if batch_texts:
107
+ collection.add(
108
+ documents=batch_texts,
109
+ embeddings=batch_embeddings,
110
+ metadatas=batch_metadatas,
111
+ ids=batch_ids
112
+ )
113
+
114
+ print(f"✅ Database created! {chunk_id} chunks indexed from {len(wiki_files)} files")
115
+
116
+ # Gemini model
117
+ available_model = 'gemini-1.5-flash-latest'
118
+
119
+ def get_embedding(text):
120
+ return embedding_model.encode(text).tolist()
121
+
122
+ def chat(message, history):
123
+ """Handle chat messages"""
124
+
125
+ try:
126
+ # Search wiki
127
+ question_embedding = get_embedding(message)
128
+ results = collection.query(
129
+ query_embeddings=[question_embedding],
130
+ n_results=5
131
+ )
132
+
133
+ relevant_chunks = results['documents'][0]
134
+ sources = results['metadatas'][0]
135
+
136
+ if not relevant_chunks:
137
+ return "I couldn't find any relevant information in the wiki."
138
+
139
+ # Build context
140
+ context = "\n\n---\n\n".join(relevant_chunks)
141
+
142
+ # Ask Gemini
143
+ model = genai.GenerativeModel(available_model)
144
+ prompt = f"""You are a Dead Cells expert. Answer using ONLY the provided wiki content.
145
+
146
+ Wiki Content:
147
+ {context}
148
+
149
+ Question: {message}
150
+
151
+ Answer based ONLY on the wiki content above:"""
152
+
153
+ response = model.generate_content(prompt)
154
+ answer = response.text
155
+
156
+ # Add sources
157
+ source_list = "\n\n📚 **Sources:** " + ", ".join(set([s['source'] for s in sources]))
158
+
159
+ return answer + source_list
160
+
161
+ except Exception as e:
162
+ return f"❌ Error: {str(e)}"
163
+
164
+ # Create Gradio interface
165
+ demo = gr.ChatInterface(
166
+ fn=chat,
167
+ title="🎮 Dead Cells Wiki Bot",
168
+ description="Ask me anything about Dead Cells! Powered by 557 wiki pages.",
169
+ examples=[
170
+ "What achievements are there for beating bosses?",
171
+ "Tell me about the Hand of the King",
172
+ "How does malaise work?",
173
+ "What are boss stem cells?",
174
+ "List some brutality weapons"
175
+ ],
176
+ theme="soft",
177
+ retry_btn=None,
178
+ undo_btn=None,
179
+ clear_btn="Clear Chat"
180
+ )
181
+
182
+ if __name__ == "__main__":
183
  demo.launch()