animesounds commited on
Commit
572c642
·
verified ·
1 Parent(s): 49f1143
Files changed (1) hide show
  1. main.py +765 -0
main.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import requests
4
+ import sqlite3
5
+ import threading
6
+ import time
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
9
+ from sentence_transformers import SentenceTransformer
10
+ from tenacity import retry, stop_after_attempt, wait_exponential
11
+ import mwparserfromhell
12
+ import logging
13
+ import chromadb
14
+ from collections import deque
15
+ from huggingface_hub import login
16
+
17
+ from fastapi import FastAPI
18
+ from pydantic import BaseModel
19
+ from fastapi.concurrency import run_in_threadpool # Import for running sync code in async app
20
+
21
+ # --- Configuration ---
22
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
23
+
24
+ CACHE_DIR = "one_piece_cache"
25
+ DB_PATH = os.path.join(CACHE_DIR, "one_piece_data.db")
26
+ CHROMA_DB_PATH = os.path.join(CACHE_DIR, "chroma_db")
27
+
28
+ # Model Selection
29
+ LLM_MODEL = "google/gemma-2-2b-it"
30
+ EMBED_MODEL = "intfloat/e5-small-v2"
31
+
32
+ # Hugging Face token
33
+ # It's recommended to pass this via environment variables in production
34
+ HF_TOKEN = os.environ.get("HF_TOKEN")
35
+
36
+ # Key One Piece categories to crawl
37
+ WIKI_CATEGORIES = {
38
+ "Characters": ["Straw_Hat_Pirates", "Marines", "Yonko", "Seven_Warlords", "Worst_Generation"],
39
+ "Devil_Fruits": ["Paramecia", "Zoan", "Logia"],
40
+ "Locations": ["Islands", "Seas", "Grand_Line", "New_World"],
41
+ "Story": ["Story_Arcs", "Sagas", "Events"],
42
+ "Organizations": ["Pirates", "Crews", "Marines", "World_Government"],
43
+ "Concepts": ["Haki", "Void_Century", "Ancient_Weapons", "Will_of_D"]
44
+ }
45
+
46
+ # Most important pages (prioritized)
47
+ CRUCIAL_PAGES = [
48
+ "Monkey_D._Luffy", "Straw_Hat_Pirates", "One_Piece_(Manga)", "Eiichiro_Oda",
49
+ "Devil_Fruit", "Haki", "Void_Century", "Gol_D._Roger", "Marines", "Yonko",
50
+ "World_Government", "Grand_Line", "New_World", "One_Piece", "Will_of_D",
51
+ "Poneglyphs", "Ancient_Weapons", "Roger_Pirates", "God_Valley_Incident",
52
+ "Joy_Boy", "Sun_God_Nika", "Laugh_Tale", "Rocks_Pirates", "Revolutionary_Army",
53
+ "Hito_Hito_no_Mi,_Model:_Nika", "Gomu_Gomu_no_Mi", "Five_Elders", "Im",
54
+ "Marshall_D._Teach", "Blackbeard_Pirates", "Gura_Gura_no_Mi", "Yami_Yami_no_Mi"
55
+ ]
56
+
57
+ # Processing Parameters
58
+ CHUNK_SIZE_TOKENS = 300
59
+ CHUNK_OVERLAP = 2
60
+ MAX_CONTEXT_CHUNKS = 10 # Increased from 8 to include more context
61
+ SIMILARITY_THRESHOLD = 0.35
62
+ REFRESH_INTERVAL = 7 * 24 * 3600 # Weekly refresh
63
+ CONVERSATION_HISTORY_LENGTH = 6 # Enhanced for better context
64
+
65
+ class OnePieceChatbot:
66
+ def __init__(self):
67
+ os.makedirs(CACHE_DIR, exist_ok=True)
68
+
69
+ # Login to Hugging Face
70
+ if HF_TOKEN:
71
+ try:
72
+ login(token=HF_TOKEN)
73
+ logging.info("Successfully logged into Hugging Face.")
74
+ except Exception as e:
75
+ logging.warning(f"Hugging Face login failed: {e}. Proceeding without explicit login.")
76
+
77
+
78
+ # Initialize database and vector store
79
+ self.db_conn = self._init_db()
80
+ self.chroma_client, self.chroma_collection = self._init_chroma()
81
+
82
+ # Initialize threading control
83
+ self.data_lock = threading.Lock()
84
+ self.processing_pages = set()
85
+ self.initial_processing_done = threading.Event() # Event to signal initial data load
86
+
87
+ # Initialize models - These are memory intensive, loaded once
88
+ try:
89
+ self.embedder = SentenceTransformer(EMBED_MODEL)
90
+ logging.info(f"Loaded SentenceTransformer model: {EMBED_MODEL}")
91
+ self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL)
92
+ logging.info(f"Loaded Tokenizer: {LLM_MODEL}")
93
+ self.model = AutoModelForCausalLM.from_pretrained(
94
+ LLM_MODEL,
95
+ device_map="auto", # Automatically select device (GPU if available)
96
+ torch_dtype=torch.bfloat16 # Use bfloat16 for efficiency
97
+ )
98
+ logging.info(f"Loaded LLM Model: {LLM_MODEL}")
99
+
100
+ # Initialize text generation pipeline
101
+ self.generator = pipeline(
102
+ "text-generation",
103
+ model=self.model,
104
+ tokenizer=self.tokenizer,
105
+ max_new_tokens=500, # Increased from 300 to avoid cut-off answers
106
+ temperature=0.2,
107
+ do_sample=True, # Set to True to match the temperature setting
108
+ repetition_penalty=1.2 # Added to reduce repetition
109
+ )
110
+ logging.info("Initialized text generation pipeline.")
111
+
112
+ except Exception as e:
113
+ logging.error(f"Failed to load models: {e}")
114
+ # Depending on requirements, you might raise the exception or handle it gracefully
115
+ # For deployment, you might want to ensure models load or the app fails early
116
+ raise SystemExit("Failed to load models, exiting.") from e
117
+
118
+ # Conversation memory (per instance, this will be global for the API)
119
+ # A more complex app might manage history per user session
120
+ self.conversation_history = deque(maxlen=CONVERSATION_HISTORY_LENGTH)
121
+
122
+ # Start background data processing thread
123
+ logging.info("Starting background data processing thread...")
124
+ thread = threading.Thread(target=self._process_wiki_data, daemon=True)
125
+ thread.start()
126
+ logging.info("Background data processing thread started.")
127
+
128
+
129
+ def _init_db(self):
130
+ """Initialize SQLite database with optimized schema."""
131
+ conn = sqlite3.connect(DB_PATH, check_same_thread=False) # check_same_thread=False is needed for FastAPI's async nature
132
+ conn.execute("""
133
+ CREATE TABLE IF NOT EXISTS wiki_data (
134
+ title TEXT PRIMARY KEY,
135
+ content TEXT,
136
+ category TEXT,
137
+ last_fetched REAL,
138
+ page_links TEXT
139
+ )
140
+ """)
141
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_category ON wiki_data (category)")
142
+ conn.commit()
143
+ logging.info(f"SQLite database initialized at {DB_PATH}")
144
+ return conn
145
+
146
+ def _init_chroma(self):
147
+ """Initialize ChromaDB for vector storage."""
148
+ client = chromadb.PersistentClient(path=CHROMA_DB_PATH)
149
+ collection_name = "one_piece_knowledge"
150
+ try:
151
+ collection = client.get_collection(name=collection_name)
152
+ logging.info(f"Connected to existing ChromaDB collection: {collection_name}")
153
+ except: # Catch exception if collection doesn't exist
154
+ collection = client.create_collection(
155
+ name=collection_name,
156
+ metadata={"hnsw:space": "cosine"} # Optimize for semantic similarity
157
+ )
158
+ logging.info(f"Created new ChromaDB collection: {collection_name}")
159
+
160
+ logging.info(f"ChromaDB initialized at {CHROMA_DB_PATH}")
161
+ return client, collection
162
+
163
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
164
+ def _fetch_wiki_page(self, title):
165
+ """Fetch a page from the One Piece wiki with improved parsing."""
166
+ logging.debug(f"Attempting to fetch wiki page: {title}")
167
+ url = f"https://onepiece.fandom.com/api.php?action=parse&page={title}&format=json&prop=wikitext|categories"
168
+ try:
169
+ response = requests.get(url, timeout=15) # Increased timeout slightly
170
+ response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
171
+ data = response.json()
172
+
173
+ if "parse" not in data:
174
+ logging.warning(f"Could not parse wiki data for {title}")
175
+ return None, [], None
176
+
177
+ wikitext = data["parse"]["wikitext"]["*"]
178
+ parsed = mwparserfromhell.parse(wikitext)
179
+
180
+ # Clean and extract text - Keep templates for now, focus on removing infoboxes/sidebars potentially
181
+ # A more robust parser might be needed for complex wiki pages
182
+ # Simple approach: remove large templates that aren't core content
183
+ for node in parsed.ifilter_templates():
184
+ # Example: remove templates starting with 'Infobox' or 'Character Infobox'
185
+ template_name = str(node.name).strip().lower()
186
+ if template_name.startswith('infobox') or 'sidebar' in template_name:
187
+ try:
188
+ parsed.remove(node)
189
+ except ValueError:
190
+ pass # Node might already be removed
191
+
192
+ # Extract internal links
193
+ links = []
194
+ for link in parsed.ifilter_wikilinks():
195
+ link_title = str(link.title).split("#")[0].strip() # Remove section links
196
+ if ":" not in link_title and len(link_title) > 1 and not link_title.startswith(('File:', 'Category:', 'Template:')):
197
+ links.append(link_title)
198
+
199
+ # Determine category
200
+ category = "Other"
201
+ if "categories" in data["parse"]:
202
+ categories = [cat["*"] for cat in data["parse"]["categories"]]
203
+ for cat_type, cat_list in WIKI_CATEGORIES.items():
204
+ if any(cat.replace(' ', '_') in [c.replace(' ', '_') for c in categories] for cat in cat_list):
205
+ category = cat_type
206
+ break
207
+
208
+ text = parsed.strip_code().strip() # Strip all wiki code
209
+ text = re.sub(r'https?://\S+', '', text) # Remove URLs
210
+ text = re.sub(r'\[\[[^\]]+\]\]', '', text) # Remove any remaining links/categories in text
211
+ text = re.sub(r'\s+', ' ', text).strip() # Normalize all whitespace to single spaces
212
+ text = re.sub(r'\n{2,}', '\n\n', text) # Normalize multiple newlines to double newline
213
+
214
+ logging.debug(f"Successfully fetched and parsed {title}, category: {category}, links found: {len(links)}")
215
+ return text, links, category
216
+
217
+ except requests.exceptions.RequestException as e:
218
+ logging.error(f"Request error fetching {title}: {e}")
219
+ raise # Re-raise to trigger retry
220
+ except Exception as e:
221
+ logging.error(f"Error processing wiki data for {title}: {e}")
222
+ return None, [], None # Return None on other errors
223
+
224
+ def _fetch_category_pages(self, category):
225
+ """Fetch all pages in a specific category."""
226
+ logging.info(f"Fetching pages for category: {category}")
227
+ url = f"https://onepiece.fandom.com/api.php?action=query&list=categorymembers&cmtitle=Category:{category}&cmlimit=500&format=json"
228
+ try:
229
+ response = requests.get(url, timeout=20) # Increased timeout
230
+ response.raise_for_status()
231
+ data = response.json()
232
+
233
+ pages = []
234
+ if "query" in data and "categorymembers" in data["query"]:
235
+ for member in data["query"]["categorymembers"]:
236
+ # Filter out specific namespaces like "File:", "Category:", etc.
237
+ if member["ns"] == 0 and "title" in member:
238
+ pages.append(member["title"])
239
+
240
+ logging.info(f"Found {len(pages)} pages in category {category}")
241
+ return pages
242
+ except requests.exceptions.RequestException as e:
243
+ logging.error(f"Request error fetching category {category}: {e}")
244
+ return []
245
+ except Exception as e:
246
+ logging.error(f"Error processing category {category} members: {e}")
247
+ return []
248
+
249
+
250
+ def _process_wiki_data(self):
251
+ """Process wiki pages and store in database and vector store."""
252
+ logging.info("Background processing: Starting data collection...")
253
+
254
+ processed_count = 0
255
+
256
+ # First process crucial pages
257
+ logging.info("Processing crucial pages...")
258
+ for page in CRUCIAL_PAGES:
259
+ # Check if already processed recently
260
+ cur = self.db_conn.execute("SELECT last_fetched FROM wiki_data WHERE title = ?", (page,))
261
+ result = cur.fetchone()
262
+ if result and time.time() - result[0] < REFRESH_INTERVAL:
263
+ logging.debug(f"Skipping recent crucial page: {page}")
264
+ processed_count += 1
265
+ continue
266
+
267
+ if self._process_page(page):
268
+ processed_count += 1
269
+
270
+
271
+ # Then fetch and process category pages
272
+ logging.info("Processing category pages...")
273
+ crawled_pages_from_categories = set()
274
+ for category_type, categories in WIKI_CATEGORIES.items():
275
+ for category in categories:
276
+ try:
277
+ pages = self._fetch_category_pages(category)
278
+ for page in pages:
279
+ # Avoid processing pages already processed or in queue from crucial list
280
+ if page in CRUCIAL_PAGES: continue
281
+ if page in crawled_pages_from_categories: continue
282
+
283
+ crawled_pages_from_categories.add(page) # Track pages found in categories
284
+
285
+ # Check if already processed recently
286
+ cur = self.db_conn.execute("SELECT last_fetched FROM wiki_data WHERE title = ?", (page,))
287
+ result = cur.fetchone()
288
+ if result and time.time() - result[0] < REFRESH_INTERVAL:
289
+ logging.debug(f"Skipping recent category page: {page}")
290
+ processed_count += 1
291
+ continue
292
+
293
+ if self._process_page(page):
294
+ processed_count += 1
295
+
296
+
297
+ except Exception as e:
298
+ logging.error(f"Error processing category {category}: {e}")
299
+
300
+ self.initial_processing_done.set() # Signal that initial processing is complete
301
+ logging.info(f"Initial data processing finished. Processed {processed_count} pages.")
302
+ logging.info(f"Vector collection count after initial processing: {self.chroma_collection.count()}")
303
+
304
+
305
+ # Periodically refresh data
306
+ while True:
307
+ time.sleep(REFRESH_INTERVAL)
308
+ logging.info("Starting periodic refresh cycle...")
309
+
310
+ # Refresh data for a batch of existing pages ordered by oldest fetch time
311
+ cur = self.db_conn.execute("SELECT title FROM wiki_data ORDER BY last_fetched ASC LIMIT 200") # Increased batch size
312
+ pages_to_refresh = [row[0] for row in cur.fetchall()]
313
+
314
+ logging.info(f"Refreshing {len(pages_to_refresh)} pages.")
315
+ for page in pages_to_refresh:
316
+ self._process_page(page) # This checks for recent fetch time internally
317
+
318
+ logging.info("Periodic refresh cycle finished.")
319
+
320
+
321
+ def _process_page(self, title):
322
+ """Process a single wiki page."""
323
+ with self.data_lock: # Use lock to prevent concurrent processing of the same page
324
+ if title in self.processing_pages:
325
+ logging.debug(f"Page {title} already in processing queue.")
326
+ return False # Indicate that processing was skipped
327
+ # Check if we *really* need to fetch this page again (double check under lock)
328
+ cur = self.db_conn.execute("SELECT last_fetched FROM wiki_data WHERE title = ?", (title,))
329
+ result = cur.fetchone()
330
+ if result and time.time() - result[0] < REFRESH_INTERVAL:
331
+ logging.debug(f"Page {title} already processed recently under lock.")
332
+ return False # Indicate that processing was skipped
333
+
334
+ self.processing_pages.add(title)
335
+ logging.info(f"Processing page: {title}")
336
+
337
+ try:
338
+ # Fetch and process the page - happens outside the initial lock
339
+ content, links, category = self._fetch_wiki_page(title)
340
+ if not content:
341
+ logging.warning(f"No content fetched for {title}")
342
+ return False # Indicate failure
343
+
344
+ # Store in SQLite (requires lock)
345
+ with self.data_lock:
346
+ self.db_conn.execute(
347
+ "INSERT OR REPLACE INTO wiki_data VALUES (?, ?, ?, ?, ?)",
348
+ (title, content, category, time.time(), ','.join(links))
349
+ )
350
+ self.db_conn.commit()
351
+ logging.debug(f"Stored {title} in SQLite.")
352
+
353
+ # Chunk and embed
354
+ chunks = self._chunk_text(content, title)
355
+ if chunks:
356
+ try:
357
+ # ChromaDB operations can be done outside the main data_lock
358
+ # but ensure ChromaDB client/collection access is thread-safe if needed,
359
+ # although PersistentClient is generally safe.
360
+ embeddings = self.embedder.encode(chunks, convert_to_tensor=False).tolist()
361
+ ids = [f"{title}::{i}" for i in range(len(chunks))]
362
+ metadatas = [{"source": title, "category": category} for _ in chunks]
363
+
364
+ # Remove old chunks for this page before upserting new ones
365
+ try:
366
+ old_ids = self.chroma_collection.get(where={"source": title}, include=[])["ids"]
367
+ if old_ids:
368
+ self.chroma_collection.delete(ids=old_ids)
369
+ logging.debug(f"Removed {len(old_ids)} old chunks for {title} from ChromaDB.")
370
+ except Exception as delete_e:
371
+ logging.warning(f"Could not delete old chunks for {title} from ChromaDB: {delete_e}")
372
+
373
+
374
+ self.chroma_collection.upsert(
375
+ ids=ids,
376
+ embeddings=embeddings,
377
+ documents=chunks,
378
+ metadatas=metadatas
379
+ )
380
+ logging.info(f"Processed {title}: {len(chunks)} chunks added to ChromaDB.")
381
+ except Exception as chroma_e:
382
+ logging.error(f"Error adding/updating chunks for {title} in ChromaDB: {chroma_e}")
383
+ # Decide if you want to re-raise or just log the error
384
+ return False # Indicate failure if vector store update fails
385
+
386
+ # Process linked pages if needed (can be done outside the main lock)
387
+ # Add linked pages to processing queue
388
+ if links:
389
+ logging.debug(f"Adding linked pages from {title} to processing queue.")
390
+ for link in links[:10]: # Limit to first 10 links to avoid too much sprawl
391
+ # Queue the page processing, don't block here
392
+ threading.Thread(target=self._process_page, args=(link,), daemon=True).start()
393
+
394
+
395
+ return True # Indicate success
396
+
397
+ except Exception as e:
398
+ logging.error(f"Caught unexpected error during processing of {title}: {e}")
399
+ return False # Indicate failure
400
+ finally:
401
+ # Ensure the page is removed from processing set even on error
402
+ with self.data_lock:
403
+ if title in self.processing_pages:
404
+ self.processing_pages.remove(title)
405
+ logging.debug(f"Removed {title} from processing queue.")
406
+
407
+
408
+ def _chunk_text(self, text, title):
409
+ """Split text into chunks for embedding with sentence awareness."""
410
+ # Use nltk for better sentence tokenization if possible, but regex is ok for a start
411
+ sentences = re.split(r'(?<=[.!?])\s+', text)
412
+ chunks, current_sentences = [], []
413
+ current_chunk_tokens = 0
414
+
415
+ # Simple check for minimal content
416
+ if len(sentences) < 2 and len(text.split()) < 50:
417
+ logging.debug(f"Page {title} is too short for chunking ({len(text.split())} words). Skipping.")
418
+ return []
419
+
420
+
421
+ for i, sentence in enumerate(sentences):
422
+ # Use tokenizer for token counting
423
+ sentence_tokens = len(self.tokenizer.encode(sentence, add_special_tokens=False))
424
+
425
+ # Check if adding the sentence would exceed chunk size OR if it's the last sentence
426
+ # If we add the sentence, what would the new token count be including a space?
427
+ # (approximate)
428
+ new_token_count = current_chunk_tokens + sentence_tokens + (1 if current_chunk_tokens > 0 else 0)
429
+
430
+ if new_token_count > CHUNK_SIZE_TOKENS and current_sentences:
431
+ # If adding sentence exceeds chunk size, save current sentences as a chunk
432
+ chunk_text = " ".join(current_sentences).strip()
433
+ if chunk_text: # Ensure chunk is not empty
434
+ chunks.append(chunk_text)
435
+ logging.debug(f"Chunked: {len(chunk_text.split())} words, {len(self.tokenizer.encode(chunk_text, add_special_tokens=False))} tokens")
436
+
437
+ # Start new chunk with overlap
438
+ overlap_sentences = current_sentences[-CHUNK_OVERLAP:] if len(current_sentences) > CHUNK_OVERLAP else current_sentences
439
+ current_sentences = overlap_sentences
440
+ current_chunk_tokens = sum(len(self.tokenizer.encode(s, add_special_tokens=False)) for s in current_sentences)
441
+
442
+ current_sentences.append(sentence)
443
+ current_chunk_tokens += sentence_tokens + (1 if current_chunk_tokens > 0 else 0) # Add space token count
444
+
445
+ # Add the last chunk if any sentences remain
446
+ if current_sentences:
447
+ chunk_text = " ".join(current_sentences).strip()
448
+ if chunk_text: # Ensure chunk is not empty
449
+ chunks.append(chunk_text)
450
+ logging.debug(f"Final Chunked: {len(chunk_text.split())} words, {len(self.tokenizer.encode(chunk_text, add_special_tokens=False))} tokens")
451
+
452
+ # Filter out chunks that are too short
453
+ return [chunk for chunk in chunks if len(chunk.split()) > 20]
454
+
455
+
456
+ def _interpret_query(self, query):
457
+ """Interpret and expand the query using conversation history."""
458
+ # Check if initial data processing is done before using history for complex interpretation
459
+ if not self.initial_processing_done.is_set() or len(query.split()) > 3 and not (query.lower().startswith("and ") or query.lower().startswith("what about ")):
460
+ # If initial data not ready, or query is already substantial, return original
461
+ return query
462
+
463
+ # Handle follow-up questions and vague queries using the LLM
464
+ logging.debug(f"Interpreting query: '{query}'")
465
+ try:
466
+ prompt = f"""
467
+ Based on this conversation history:
468
+ {self._format_history()}
469
+
470
+ The user asked a question: "{query}"
471
+ Please interpret this as a complete, standalone question about One Piece, incorporating context from the history if necessary. Ensure the reformulated question is clear and specific, even if the original query was vague or a follow-up.
472
+ Only provide the complete reformulated question and nothing else.
473
+ """
474
+ # Use the generator for interpretation
475
+ # Set max_new_tokens low as we only expect a short question
476
+ interpretation_response = self.generator(
477
+ prompt,
478
+ max_new_tokens=50,
479
+ temperature=0.5,
480
+ do_sample=True,
481
+ repetition_penalty=1.1
482
+ )[0]["generated_text"]
483
+
484
+ # Extract the reformulated question (look for the part after the instruction)
485
+ # This is a bit fragile, depends on LLM output format
486
+ if "Only provide the complete reformulated question and nothing else:" in interpretation_response:
487
+ interpreted_query = interpretation_response.split("Only provide the complete reformulated question and nothing else:")[-1].strip()
488
+ else:
489
+ # Fallback if the LLM doesn't follow the format strictly
490
+ # Try to clean up surrounding text
491
+ lines = interpreted_query.split('\n')
492
+ interpreted_query = lines[-1].strip() if lines else interpreted_query.strip()
493
+
494
+
495
+ # Basic cleaning
496
+ interpreted_query = interpreted_query.replace('"', '').strip()
497
+ logging.info(f"Interpreted '{query}' as '{interpreted_query}'")
498
+ return interpreted_query
499
+
500
+ except Exception as e:
501
+ logging.error(f"Error interpreting query '{query}': {e}. Using original query.")
502
+ return query # Fallback to original query on error
503
+
504
+
505
+ def _find_relevant_chunks(self, query):
506
+ """Find relevant chunks using vector similarity."""
507
+ # Wait briefly for initial data if not ready. Avoid long blocking.
508
+ if not self.initial_processing_done.is_set():
509
+ logging.warning("Initial data processing not complete. Search results may be limited.")
510
+ # Give it a few seconds just in case it's almost done, but don't block indefinitely
511
+ self.initial_processing_done.wait(timeout=5) # Wait up to 5 seconds
512
+
513
+ interpreted_query = self._interpret_query(query)
514
+
515
+ # Enhanced query expansion for key topics - performed *after* interpretation
516
+ # This adds specific keywords to the query that might help retrieve relevant documents
517
+ keywords_to_add = []
518
+ lower_query = interpreted_query.lower()
519
+
520
+ if "joy boy" in lower_query or "nika" in lower_query:
521
+ keywords_to_add.extend(["Hito Hito no Mi Model Nika", "Sun God Nika"])
522
+ if "blackbeard" in lower_query and "devil fruit" in lower_query:
523
+ keywords_to_add.extend(["multiple devil fruits", "Yami Yami no Mi", "Gura Gura no Mi"])
524
+ if "gorosei" in lower_query or "im" in lower_query:
525
+ keywords_to_add.extend(["Five Elders", "Empty Throne", "World Government"])
526
+ if "void century" in lower_query:
527
+ keywords_to_add.extend(["Poneglyphs", "Ancient Kingdom", "Ohara"])
528
+
529
+
530
+ if keywords_to_add:
531
+ interpreted_query_with_keywords = interpreted_query + " " + " ".join(keywords_to_add)
532
+ logging.debug(f"Expanded query: {interpreted_query_with_keywords}")
533
+ else:
534
+ interpreted_query_with_keywords = interpreted_query
535
+
536
+
537
+ # Search vector database
538
+ try:
539
+ query_embedding = self.embedder.encode(interpreted_query_with_keywords).tolist()
540
+ results = self.chroma_collection.query(
541
+ query_embeddings=[query_embedding],
542
+ n_results=MAX_CONTEXT_CHUNKS,
543
+ include=["documents", "metadatas", "distances"]
544
+ )
545
+ except Exception as e:
546
+ logging.error(f"Error querying ChromaDB: {e}")
547
+ return [], [] # Return empty if search fails
548
+
549
+
550
+ chunks = []
551
+ sources = set() # Use a set to keep sources unique
552
+
553
+ if results and results["documents"]:
554
+ # Only include chunks above similarity threshold
555
+ for i, doc in enumerate(results["documents"][0]):
556
+ distance = results["distances"][0][i]
557
+ similarity = 1 - distance # Cosine distance is 1 - cosine similarity
558
+
559
+ logging.debug(f"Chunk {i+1}: Source={results['metadatas'][0][i]['source']}, Distance={distance:.4f}, Similarity={similarity:.4f}")
560
+
561
+ if similarity >= SIMILARITY_THRESHOLD:
562
+ chunks.append(doc)
563
+ sources.add(results["metadatas"][0][i]["source"])
564
+
565
+ logging.info(f"Found {len(chunks)} relevant chunks for query '{query}'. Sources: {list(sources)}")
566
+ return chunks, list(sources)
567
+
568
+
569
+ def _extract_entities(self, text):
570
+ """Extract potential One Piece entities from text."""
571
+ # This method isn't currently used in answer_question, but kept from original.
572
+ # Simple heuristic: look for capitalized words that might be names/places
573
+ entities = re.findall(r'\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b', text)
574
+ # Filter out common English words and short words that aren't likely entities
575
+ common_words = {"The", "A", "An", "In", "On", "At", "For", "With", "And", "But", "Or", "Not", "Is", "Are", "Was", "Were"}
576
+ return [e for e in entities if len(e) > 3 and e not in common_words]
577
+
578
+
579
+ def _format_history(self):
580
+ """Format conversation history for the LLM prompt."""
581
+ if not self.conversation_history:
582
+ return "No recent conversation history."
583
+
584
+ history = "Recent conversation history:\n"
585
+ for i, (q, a) in enumerate(self.conversation_history):
586
+ history += f"Turn {i+1}:\nUser: {q}\nAssistant: {a}\n"
587
+ return history
588
+
589
+ def answer_question(self, question: str):
590
+ """Answer a question using retrieved context and conversation history."""
591
+ logging.info(f"Received question: '{question}'")
592
+
593
+ # Wait for initial data processing if not finished.
594
+ # This makes the first few requests potentially slower but ensures some data is loaded.
595
+ # Consider a proper "loading" status endpoint if this is too slow.
596
+ if not self.initial_processing_done.is_set():
597
+ logging.warning("Initial data processing not yet complete. Waiting up to 60s...")
598
+ if not self.initial_processing_done.wait(timeout=60):
599
+ logging.error("Initial data processing timed out. Cannot answer reliably.")
600
+ return "The knowledge base is still loading. Please try again in a few minutes."
601
+ else:
602
+ logging.info("Initial data processing finished while waiting.")
603
+
604
+
605
+ chunks, sources = self._find_relevant_chunks(question)
606
+
607
+ if not chunks:
608
+ logging.warning(f"No relevant chunks found for question: '{question}'")
609
+ # Add a fallback or a "I don't know" response if no context is found
610
+ fallback_prompt = f"""You are an expert on the One Piece manga and anime. The user asked: "{question}". However, no relevant specific information was found in your knowledge base. Provide a general, helpful answer based on your broad understanding of One Piece, or state that you don't have specific information on this topic. Do not invent facts.
611
+
612
+ IMPORTANT: Start immediately with your answer."""
613
+ try:
614
+ response = self.generator(fallback_prompt, max_new_tokens=200, temperature=0.7, do_sample=True)[0]["generated_text"].strip()
615
+ # Clean up prompt instructions
616
+ response = re.sub(r'^.*?IMPORTANT: Start immediately with your answer\.', '', response, flags=re.DOTALL).strip()
617
+ answer = response
618
+ # Add to history (can decide if you want "I don't know" in history)
619
+ self.conversation_history.append((question, answer))
620
+ return answer
621
+ except Exception as e:
622
+ logging.error(f"Error generating fallback response: {e}")
623
+ answer = "I couldn't find specific information about that in my knowledge base."
624
+ self.conversation_history.append((question, answer))
625
+ return answer
626
+
627
+
628
+ # Construct the prompt for the LLM
629
+ # Enhanced prompt with clear output instructions
630
+ prompt = f"""You are an expert on the One Piece manga and anime. Answer the following question based *only* on the provided context and your knowledge of One Piece lore.
631
+
632
+ {self._format_history()}
633
+
634
+ Context information:
635
+ {chr(10).join(chunks)}
636
+
637
+ Question: {question}
638
+
639
+ Provide a detailed, accurate answer based on the context above. If the context doesn't contain enough information to fully answer, use your general One Piece knowledge but prioritize information from the context. Explain connections between characters and events clearly. Structure your answer logically.
640
+
641
+ IMPORTANT: Your answer must be directly useful and not include phrases like "based on the context" or "answer the question". Start immediately with your answer. Ensure your answer is cohesive and well-formatted.
642
+ """
643
+
644
+ logging.debug(f"Sending prompt to LLM:\n{prompt}")
645
+
646
+ try:
647
+ # Get the response from the generator pipeline
648
+ response = self.generator(prompt)[0]["generated_text"]
649
+ logging.debug(f"Raw LLM response:\n{response}")
650
+
651
+ # Extract just the answer portion and clean it
652
+ # Use a pattern that matches the instruction part robustly
653
+ answer_match = re.search(r'IMPORTANT:.*?Start immediately with your answer\.(.*)', response, re.DOTALL)
654
+ if answer_match:
655
+ answer = answer_match.group(1).strip()
656
+ else:
657
+ # Fallback extraction if the instruction pattern is not found
658
+ # Attempt to find the question again and take everything after it
659
+ answer_parts = response.split("Question: " + question)
660
+ if len(answer_parts) > 1:
661
+ answer = answer_parts[-1].strip()
662
+ else:
663
+ # If still not found, take the last significant block or the whole thing
664
+ logging.warning("Could not find extraction pattern, falling back to end of response.")
665
+ answer = response.strip() # Or implement more sophisticated fallback logic
666
+
667
+
668
+ # Clean up any lingering prompt instructions or metadata accidentally generated
669
+ answer = re.sub(r'^(.*?)(?:IMPORTANT:|Based on this conversation history:|Context information:|Question:)', '', answer, flags=re.DOTALL | re.IGNORECASE).strip()
670
+ answer = re.sub(r'\s*Sources:\s*.*$', '', answer, flags=re.DOTALL) # Remove any "Sources:" line the LLM might invent
671
+
672
+
673
+ except Exception as e:
674
+ logging.error(f"Error generating response from LLM: {e}")
675
+ answer = "Sorry, I encountered an error while generating the response."
676
+
677
+
678
+ # Add to conversation history (user question and generated answer)
679
+ self.conversation_history.append((question, answer))
680
+ logging.debug(f"Added to history: Q='{question}', A='{answer[:50]}...'")
681
+
682
+ # Format response with better source attribution
683
+ if sources:
684
+ # Ensure sources are clean titles, not links or complex text
685
+ clean_sources = [s.replace('_', ' ') for s in sources] # Simple cleaning
686
+ sources_list = list(clean_sources)[:5] # Limit to top 5 sources for brevity in output
687
+ sources_str = ", ".join(sources_list)
688
+ # Append sources clearly
689
+ return f"{answer}\n\nSources: {sources_str}"
690
+
691
+ return answer
692
+
693
+ # --- FastAPI Application Setup ---
694
+
695
+ # Initialize the chatbot instance globally
696
+ # This happens when the script is first imported/run, loading models and starting threads
697
+ try:
698
+ chatbot = OnePieceChatbot()
699
+ logging.info("OnePieceChatbot instance created.")
700
+ except Exception as e:
701
+ logging.critical(f"Failed to initialize OnePieceChatbot: {e}")
702
+ # In a real deployment, this might stop the container or signal an error
703
+ # For now, we'll let the app start but requests will likely fail
704
+
705
+ app = FastAPI()
706
+
707
+ # Pydantic model for the request body
708
+ class QuestionRequest(BaseModel):
709
+ question: str
710
+
711
+ # Root endpoint
712
+ @app.get("/")
713
+ async def read_root():
714
+ return {"message": "One Piece Chatbot API is running. Send a POST request to /ask with your question."}
715
+
716
+ # Health check endpoint
717
+ @app.get("/health")
718
+ async def health_check():
719
+ # Add more sophisticated checks here if needed (e.g., db connection, model loaded)
720
+ if not hasattr(chatbot, 'generator') or chatbot.generator is None:
721
+ return {"status": "error", "message": "LLM model not loaded"}, 500
722
+
723
+ # Check if the background thread has completed initial processing
724
+ if not chatbot.initial_processing_done.is_set():
725
+ return {"status": "warning", "message": "Initial data processing still in progress. Some answers may be limited."}, 200 # Or 503 Service Unavailable
726
+
727
+ # Optional: Check ChromaDB count to ensure it's not empty after initialization
728
+ try:
729
+ count = chatbot.chroma_collection.count()
730
+ if count == 0:
731
+ return {"status": "warning", "message": "Knowledge base is empty after initialization. Data fetching might have failed."}, 200
732
+ return {"status": "ok", "message": "Chatbot is ready.", "knowledge_base_size": count}, 200
733
+ except Exception as e:
734
+ logging.error(f"Health check failed during ChromaDB count: {e}")
735
+ return {"status": "warning", "message": f"Health check encountered an issue: {e}"}, 200
736
+
737
+
738
+ # Endpoint to answer questions
739
+ @app.post("/ask")
740
+ async def ask_question_endpoint(request: QuestionRequest):
741
+ """
742
+ Submit a question about One Piece and get an answer.
743
+ """
744
+ question = request.question
745
+ if not question or not question.strip():
746
+ return {"answer": "Please provide a question."}
747
+
748
+ # Run the synchronous answer_question method in a thread pool
749
+ # This prevents blocking the FastAPI event loop
750
+ try:
751
+ answer = await run_in_threadpool(chatbot.answer_question, question)
752
+ return {"answer": answer}
753
+ except Exception as e:
754
+ logging.error(f"Error processing question '{question}': {e}")
755
+ return {"answer": "Sorry, an internal error occurred while processing your question."}, 500 # Return 500 status code on error
756
+
757
+ # To run this application:
758
+ # 1. Save the code as a Python file (e.g., main.py).
759
+ # 2. Make sure you have the necessary libraries installed:
760
+ # pip install fastapi uvicorn transformers sentence-transformers tenacity mwparserfromhell chromadb requests sqlite3 accelerate bitsandbytes torch huggingface_hub
761
+ # (You might need additional dependencies for torch/accelerate based on your hardware, e.g., CUDA)
762
+ # 3. Run from your terminal: uvicorn main:app --reload
763
+ # For deployment, you'll typically use a production server like Gunicorn with Uvicorn workers:
764
+ # gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
765
+ # Ensure the HF_TOKEN environment variable is set in your deployment environment.