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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
from typing import List, Dict, Optional, Tuple
import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor, AutoTokenizer
from qwen_vl_utils import process_vision_info
from PIL import Image
import io


class TokenChunker:
    """Handle token counting and chunking for model context limits."""
    
    def __init__(self, model_name: str = "Qwen/Qwen2.5-VL-3B-Instruct"):
        """Initialize tokenizer for token counting."""
        self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
        # Qwen2.5-VL has max context of 131,072 tokens
        self.max_tokens = 100000  # Conservative limit (use 100K of 131K available)
    
    def count_tokens(self, text: str) -> int:
        """Count tokens in text."""
        try:
            tokens = self.tokenizer.encode(text, add_special_tokens=False)
            return len(tokens)
        except Exception as e:
            print(f"Error counting tokens: {e}")
            # Rough estimate: 1 token ≈ 4 characters for English/Russian
            return len(text) // 4
    
    def chunk_text(self, text: str, chunk_size: int = 50000) -> List[str]:
        """Split text into chunks that fit within token limits."""
        if len(text) <= chunk_size:
            return [text]
        
        chunks = []
        current_chunk = ""
        
        # Split by paragraphs first
        paragraphs = text.split("\n\n")
        
        for paragraph in paragraphs:
            if len(current_chunk) + len(paragraph) < chunk_size:
                current_chunk += paragraph + "\n\n"
            else:
                if current_chunk:
                    chunks.append(current_chunk.strip())
                current_chunk = paragraph + "\n\n"
        
        if current_chunk:
            chunks.append(current_chunk.strip())
        
        return chunks
    
    def truncate_to_token_limit(self, text: str, token_limit: int = 50000) -> str:
        """Truncate text to fit within token limit."""
        current_tokens = self.count_tokens(text)
        
        if current_tokens <= token_limit:
            return text
        
        print(f"Text too long ({current_tokens} tokens). Truncating to {token_limit}...")
        
        # Estimate characters per token
        char_per_token = len(text) / current_tokens
        target_chars = int(token_limit * char_per_token * 0.9)  # 90% to be safe
        
        truncated = text[:target_chars]
        return truncated


class Qwen25VLInferencer:
    """Handle inference with Qwen2.5-VL-3B model - FIXED meta tensor issue."""
    
class Qwen25VLInferencer:
    """Handle inference with Qwen2.5-VL-3B model - FIXED meta tensor issue."""
    
    def __init__(self, model_name: str = "Qwen/Qwen2.5-VL-3B-Instruct", device: str = "cuda"):
        """Initialize Qwen2.5-VL model with proper device handling."""
        self.device = device if torch.cuda.is_available() else "cpu"
        print(f"Loading Qwen2.5-VL-3B model on device: {self.device}")
        
        try:
            # FIXED: Load model without device_map first, then move to device
            # This avoids the meta tensor issue
            
            # Determine data type based on device
            if self.device == "cuda":
                dtype = torch.float16  # GPU: use half precision
            else:
                dtype = torch.float32  # CPU: use full precision
            
            print(f"Using dtype: {dtype}")
            
            # Load model
            print("Loading model weights...")
            self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
                model_name,
                torch_dtype=dtype,
                trust_remote_code=True,
                # IMPORTANT: Don't use device_map="auto" here - causes meta tensor issue
            )
            
            # Move to device explicitly AFTER loading
            print(f"Moving model to {self.device}...")
            if self.device == "cuda":
                self.model = self.model.to("cuda")
            else:
                self.model = self.model.to("cpu")
            
            # Set to evaluation mode
            self.model.eval()
            
            print("✅ Model loaded successfully")
            
        except RuntimeError as e:
            if "meta tensor" in str(e):
                print(f"⚠️ Meta tensor error detected: {e}")
                print("Falling back to CPU mode...")
                self.device = "cpu"
                
                self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
                    model_name,
                    torch_dtype=torch.float32,
                    trust_remote_code=True,
                )
                self.model = self.model.to("cpu")
                self.model.eval()
                print("✅ Model loaded on CPU")
            else:
                raise
        
        except Exception as e:
            print(f"❌ Error loading model: {e}")
            print("Trying fallback CPU loading...")
            
            self.device = "cpu"
            self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
                model_name,
                torch_dtype=torch.float32,
                trust_remote_code=True,
            )
            self.model = self.model.to("cpu")
            self.model.eval()
        
        # Load processor
        print("Loading processor...")
        self.processor = AutoProcessor.from_pretrained(
            model_name,
            trust_remote_code=True
        )
        
        # Initialize token chunker
        self.token_chunker = TokenChunker(model_name)
        
        print("✅ Model initialization complete")
    
    def _prepare_text_message(self, text: str) -> List[Dict]:
        """Prepare text-only message for the model."""
        return [{"type": "text", "text": text}]
    
    def _prepare_image_text_message(self, image_path: str, text: str) -> List[Dict]:
        """Prepare message with image and text."""
        return [
            {"type": "image", "image": image_path},
            {"type": "text", "text": text}
        ]
    
    def generate_answer(
        self,
        query: str,
        retrieved_docs: List[Dict],
        retrieved_images: List[str] = None,
        max_new_tokens: int = 128
    ) -> str:
        """
        Generate answer based on query and retrieved documents.
        FIXED: Includes token chunking and context length management
        """
        # Build context from retrieved documents
        context = "КОНТЕКСТ ИЗ ДОКУМЕНТОВ:\n"
        for doc in retrieved_docs:
            relevance = doc.get('relevance_score', 0)
            context += f"\n[Релевантность: {relevance:.2f}]\n{doc['document']}\n"
        
        # FIXED: Truncate context if too long
        context = self.token_chunker.truncate_to_token_limit(context, token_limit=50000)
        
        # Build system prompt
        system_prompt = "Ты помощник для анализа документов. Используй предоставленный контекст для ответа на вопросы. Отвечай на русском языке. Будь кратким и точным."
        
        # Prepare the full query
        full_query = f"{system_prompt}\n\n{context}\n\nВопрос: {query}\n\nОтвет:"
        
        # FIXED: Check and limit token count
        query_tokens = self.token_chunker.count_tokens(full_query)
        print(f"Query token count: {query_tokens}")
        
        if query_tokens > 100000:
            print(f"Query exceeds token limit. Reducing context...")
            # Keep only first 3 documents instead of all
            context = "КОНТЕКСТ ИЗ ДОКУМЕНТОВ:\n"
            for doc in retrieved_docs[:3]:
                relevance = doc.get('relevance_score', 0)
                context += f"\n[Релевантность: {relevance:.2f}]\n{doc['document']}\n"
            
            context = self.token_chunker.truncate_to_token_limit(context, token_limit=30000)
            full_query = f"{system_prompt}\n\n{context}\n\nВопрос: {query}\n\nОтвет:"
        
        # Prepare messages
        messages = self._prepare_text_message(full_query)
        
        # If images are provided, add them
        if retrieved_images and len(retrieved_images) > 0:
            try:
                image_message = self._prepare_image_text_message(
                    retrieved_images[0],
                    f"Проанализируй это изображение в контексте вопроса: {query}"
                )
                messages = image_message + [{"type": "text", "text": full_query}]
            except Exception as e:
                print(f"Warning: Could not include images: {e}")
        
        # Process vision info if images are included
        image_inputs = []
        video_inputs = []
        
        try:
            if any(msg.get('type') == 'image' for msg in messages):
                image_inputs, video_inputs = process_vision_info(messages)
        except Exception as e:
            print(f"Warning: Could not process images: {e}")
        
        # Prepare inputs for model
        try:
            inputs = self.processor(
                text=[full_query],
                images=image_inputs if image_inputs else None,
                videos=video_inputs if video_inputs else None,
                padding=True,
                return_tensors='pt',
            )
        except Exception as e:
            print(f"Error preparing inputs: {e}")
            return f"Error preparing inputs: {e}"
        
        # Move inputs to device
        if self.device == "cuda":
            inputs = inputs.to("cuda")
        
        # Generate response with error handling
        try:
            with torch.no_grad():
                generated_ids = self.model.generate(
                    **inputs,
                    max_new_tokens=min(max_new_tokens, 512),  # Cap at 512
                    num_beams=1,
                    do_sample=False
                )
        except Exception as e:
            print(f"Error during generation: {e}")
            return f"Error generating response: {e}"
        
        # Decode output
        try:
            generated_ids_trimmed = [
                out_ids[len(in_ids):] 
                for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
            ]
            
            response = self.processor.batch_decode(
                generated_ids_trimmed,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=False
            )
            
            return response[0] if response else "Could not generate response"
        except Exception as e:
            print(f"Error decoding response: {e}")
            return f"Error decoding response: {e}"
    
    def summarize_document(
        self,
        document_text: str,
        max_new_tokens: int = 512
    ) -> str:
        """Summarize a document with token limit management."""
        
        # FIXED: Truncate document to fit in context
        document_text = self.token_chunker.truncate_to_token_limit(
            document_text,
            token_limit=40000
        )
        
        prompt = f"""Пожалуйста, создай подробное резюме следующего документа на русском языке.
        
Документ:
{document_text}

Резюме:"""
        
        messages = self._prepare_text_message(prompt)
        
        try:
            inputs = self.processor(
                text=[prompt],
                padding=True,
                return_tensors='pt',
            )
            
            if self.device == "cuda":
                inputs = inputs.to("cuda")
            
            with torch.no_grad():
                generated_ids = self.model.generate(
                    **inputs,
                    max_new_tokens=min(max_new_tokens, 512),
                    num_beams=1,
                    do_sample=False
                )
            
            generated_ids_trimmed = [
                out_ids[len(in_ids):] 
                for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
            ]
            
            response = self.processor.batch_decode(
                generated_ids_trimmed,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=False
            )
            
            return response[0] if response else "Could not generate summary"
        except Exception as e:
            print(f"Error generating summary: {e}")
            return f"Error: {e}"


class RAGPipeline:
    """Complete RAG pipeline combining retrieval and generation."""
    
    def __init__(self, chroma_manager, device: str = "cuda"):
        """Initialize RAG pipeline."""
        self.chroma_manager = chroma_manager
        self.inferencer = Qwen25VLInferencer(device=device)
    
    def answer_question(
        self,
        query: str,
        n_retrieved: int = 5,
        max_new_tokens: int = 512
    ) -> Dict:
        """
        Answer user question using RAG pipeline.
        1. Retrieve relevant documents
        2. Generate answer using Qwen2.5-VL
        """
        # Step 1: Retrieve
        retrieved_docs = self.chroma_manager.search(query, n_results=n_retrieved)
        
        if not retrieved_docs:
            return {
                "answer": "Не найдены релевантные документы для ответа на вопрос.",
                "retrieved_docs": [],
                "query": query,
                "error": "No documents found"
            }
        
        # Extract images from retrieved results if available
        retrieved_images = []
        
        # Step 2: Generate
        try:
            answer = self.inferencer.generate_answer(
                query=query,
                retrieved_docs=retrieved_docs,
                retrieved_images=retrieved_images,
                max_new_tokens=max_new_tokens
            )
        except Exception as e:
            answer = f"Error generating answer: {e}"
        
        return {
            "answer": answer,
            "retrieved_docs": retrieved_docs,
            "query": query,
            "model": "Qwen2.5-VL-3B",
            "doc_count": len(retrieved_docs)
        }
    
    def summarize_all_documents(self, max_chars: int = 100000) -> str:
        """Create summary of all indexed documents with token limits."""
        collection_info = self.chroma_manager.get_collection_info()
        doc_count = collection_info['document_count']
        
        if doc_count == 0:
            return "No documents in database to summarize."
        
        # Retrieve documents
        try:
            all_docs = self.chroma_manager.collection.get(include=['documents'])
            
            if not all_docs['documents']:
                return "Could not retrieve documents for summarization."
            
            # Combine first documents with char limit
            combined_text = ""
            for doc in all_docs['documents'][:10]:  # Max 10 docs
                if len(combined_text) + len(doc) < max_chars:
                    combined_text += doc + "\n\n"
                else:
                    break
            
            if not combined_text:
                combined_text = all_docs['documents'][0][:max_chars]
            
            summary = self.inferencer.summarize_document(combined_text)
            return summary
        except Exception as e:
            return f"Error summarizing documents: {e}"