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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# #!/usr/bin/env python3
# """
# Local setup script for Manufacturing RAG Agent without Docker.

# This script helps set up the RAG system using Qdrant Cloud or local alternatives.
# """

# import os
# import sys
# import subprocess
# from pathlib import Path
# import requests
# import time

# def check_python_version():
#     """Check if Python version is compatible."""
#     if sys.version_info < (3, 8):
#         print("❌ Python 3.8+ is required")
#         return False
#     print(f"βœ… Python {sys.version_info.major}.{sys.version_info.minor} detected")
#     return True

# def check_dependencies():
#     """Check if required dependencies are installed."""
#     print("\nπŸ” Checking dependencies...")
    
#     # Check pip packages
#     required_packages = [
#         'streamlit', 'qdrant-client', 'groq', 'requests',
#         'pandas', 'plotly', 'PyMuPDF', 'openpyxl', 'pytesseract', 'Pillow'
#     ]
    
#     missing_packages = []
#     for package in required_packages:
#         try:
#             __import__(package.replace('-', '_').lower())
#             print(f"βœ… {package}")
#         except ImportError:
#             print(f"❌ {package}")
#             missing_packages.append(package)
    
#     if missing_packages:
#         print(f"\nπŸ“¦ Installing missing packages: {', '.join(missing_packages)}")
#         try:
#             subprocess.check_call([
#                 sys.executable, '-m', 'pip', 'install'
#             ] + missing_packages)
#             print("βœ… All packages installed successfully")
#         except subprocess.CalledProcessError:
#             print("❌ Failed to install packages")
#             return False
    
#     return True

# def check_tesseract():
#     """Check if Tesseract OCR is installed."""
#     print("\nπŸ” Checking Tesseract OCR...")
#     try:
#         result = subprocess.run(['tesseract', '--version'], 
#                               capture_output=True, text=True)
#         if result.returncode == 0:
#             version = result.stdout.split('\n')[0]
#             print(f"βœ… {version}")
#             return True
#     except FileNotFoundError:
#         pass
    
#     print("❌ Tesseract OCR not found")
#     print("πŸ“₯ Install with: brew install tesseract")
#     return False

# def setup_environment():
#     """Set up environment variables."""
#     print("\nβš™οΈ Setting up environment...")
    
#     env_file = Path('.env')
#     env_example = Path('.env.example')
    
#     if not env_file.exists() and env_example.exists():
#         # Copy example file
#         with open(env_example, 'r') as f:
#             content = f.read()
        
#         with open(env_file, 'w') as f:
#             f.write(content)
        
#         print("βœ… Created .env file from template")
#         print("πŸ“ Please edit .env file with your API keys:")
#         print("   - GROQ_API_KEY (get from https://console.groq.com/)")
#         print("   - SILICONFLOW_API_KEY (get from https://siliconflow.cn/)")
#         print("   - QDRANT_URL and QDRANT_API_KEY (if using Qdrant Cloud)")
#         return False
#     elif env_file.exists():
#         print("βœ… .env file exists")
#         return True
#     else:
#         print("❌ No .env.example file found")
#         return False

# def test_qdrant_connection():
#     """Test Qdrant connection."""
#     print("\nπŸ” Testing Qdrant connection...")
    
#     # Try local Qdrant first
#     try:
#         response = requests.get('http://localhost:6333/health', timeout=5)
#         if response.status_code == 200:
#             print("βœ… Local Qdrant is running")
#             return True
#     except requests.exceptions.RequestException:
#         pass
    
#     # Try Qdrant Cloud if configured
#     qdrant_url = os.getenv('QDRANT_URL')
#     qdrant_key = os.getenv('QDRANT_API_KEY')
    
#     if qdrant_url and qdrant_key:
#         try:
#             headers = {'api-key': qdrant_key} if qdrant_key else {}
#             response = requests.get(f"{qdrant_url}/health", headers=headers, timeout=10)
#             if response.status_code == 200:
#                 print("βœ… Qdrant Cloud connection successful")
#                 return True
#         except requests.exceptions.RequestException as e:
#             print(f"❌ Qdrant Cloud connection failed: {e}")
    
#     print("❌ No Qdrant connection available")
#     print("πŸ’‘ Options:")
#     print("   1. Start local Qdrant: docker run -p 6333:6333 qdrant/qdrant")
#     print("   2. Use Qdrant Cloud: https://cloud.qdrant.io/")
#     print("   3. Download Qdrant binary: https://github.com/qdrant/qdrant/releases")
#     return False

# def create_data_directories():
#     """Create necessary data directories."""
#     print("\nπŸ“ Creating data directories...")
    
#     directories = [
#         'data',
#         'data/documents',
#         'logs',
#         'results'
#     ]
    
#     for directory in directories:
#         Path(directory).mkdir(parents=True, exist_ok=True)
#         print(f"βœ… {directory}/")
    
#     return True

# def test_api_keys():
#     """Test API key configuration."""
#     print("\nπŸ”‘ Testing API keys...")
    
#     # Load environment variables
#     from dotenv import load_dotenv
#     load_dotenv()
    
#     # Test Groq API
#     groq_key = os.getenv('GROQ_API_KEY')
#     if groq_key:
#         try:
#             headers = {'Authorization': f'Bearer {groq_key}'}
#             response = requests.get('https://api.groq.com/openai/v1/models', 
#                                   headers=headers, timeout=10)
#             if response.status_code == 200:
#                 print("βœ… Groq API key is valid")
#             else:
#                 print(f"❌ Groq API key test failed: {response.status_code}")
#         except requests.exceptions.RequestException as e:
#             print(f"❌ Groq API connection failed: {e}")
#     else:
#         print("❌ GROQ_API_KEY not set")
    
#     # Test Silicon Flow API
#     sf_key = os.getenv('SILICONFLOW_API_KEY')
#     if sf_key:
#         print("βœ… Silicon Flow API key is set (cannot test without making API call)")
#     else:
#         print("❌ SILICONFLOW_API_KEY not set")
    
#     return groq_key and sf_key

# def main():
#     """Main setup function."""
#     print("🏭 Manufacturing RAG Agent Setup")
#     print("=" * 40)
    
#     # Check Python version
#     if not check_python_version():
#         sys.exit(1)
    
#     # Check dependencies
#     if not check_dependencies():
#         print("\n❌ Dependency check failed")
#         sys.exit(1)
    
#     # Check Tesseract
#     tesseract_ok = check_tesseract()
    
#     # Setup environment
#     env_setup = setup_environment()
    
#     # Create directories
#     create_data_directories()
    
#     if env_setup:
#         # Test API keys
#         api_keys_ok = test_api_keys()
        
#         # Test Qdrant
#         qdrant_ok = test_qdrant_connection()
        
#         print("\n" + "=" * 40)
#         print("πŸ“‹ Setup Summary:")
#         print(f"βœ… Python: OK")
#         print(f"βœ… Dependencies: OK")
#         print(f"{'βœ…' if tesseract_ok else '❌'} Tesseract OCR: {'OK' if tesseract_ok else 'Missing'}")
#         print(f"{'βœ…' if api_keys_ok else '❌'} API Keys: {'OK' if api_keys_ok else 'Missing'}")
#         print(f"{'βœ…' if qdrant_ok else '❌'} Qdrant: {'OK' if qdrant_ok else 'Not available'}")
        
#         if tesseract_ok and api_keys_ok and qdrant_ok:
#             print("\nπŸŽ‰ Setup complete! You can now run:")
#             print("   python launch_rag_demo.py")
#         else:
#             print("\n⚠️  Setup incomplete. Please address the issues above.")
#             if not tesseract_ok:
#                 print("   Install Tesseract: brew install tesseract")
#             if not api_keys_ok:
#                 print("   Configure API keys in .env file")
#             if not qdrant_ok:
#                 print("   Set up Qdrant (see options above)")
#     else:
#         print("\nπŸ“ Please configure your .env file with API keys, then run this script again.")

# if __name__ == "__main__":
#     main()





#!/usr/bin/env python3
"""
Quick fix script for Manufacturing RAG Agent issues
"""

import os
import sys
from dotenv import load_dotenv
from qdrant_client import QdrantClient
from qdrant_client.http import models
import requests

load_dotenv()

def check_environment():
    """Check all environment variables."""
    print("πŸ” Checking Environment Variables")
    print("=" * 40)
    
    required_vars = {
        'GROQ_API_KEY': 'Groq LLM API',
        'SILICONFLOW_API_KEY': 'SiliconFlow Embedding API', 
        'QDRANT_URL': 'Qdrant Vector Database URL',
        'QDRANT_API_KEY': 'Qdrant API Key'
    }
    
    issues = []
    
    for var, description in required_vars.items():
        value = os.getenv(var)
        if value:
            # Mask sensitive info
            if 'KEY' in var:
                display_value = f"{value[:8]}...{value[-4:]}" if len(value) > 12 else "***"
            else:
                display_value = value
            print(f"βœ… {var}: {display_value}")
        else:
            print(f"❌ {var}: Not set")
            issues.append(f"{var} ({description})")
    
    if issues:
        print(f"\n❌ Missing environment variables:")
        for issue in issues:
            print(f"   - {issue}")
        return False
    
    return True

def test_siliconflow_api():
    """Test SiliconFlow API connection and get actual embedding dimensions."""
    print("\nπŸ§ͺ Testing SiliconFlow API")
    print("=" * 30)
    
    api_key = os.getenv('SILICONFLOW_API_KEY')
    if not api_key:
        print("❌ No API key found")
        return None
    
    try:
        payload = {
            "model": "Qwen/Qwen3-Embedding-8B",
            "input": ["test embedding to check dimensions"],
            "encoding_format": "float"
        }
        
        headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
        
        print("πŸ“‘ Testing API connection...")
        response = requests.post(
            "https://api.siliconflow.com/v1/embeddings",
            json=payload,
            headers=headers,
            timeout=15
        )
        
        if response.status_code == 200:
            data = response.json()
            if 'data' in data and len(data['data']) > 0:
                embedding = data['data'][0]['embedding']
                dimensions = len(embedding)
                print(f"βœ… API working! Embedding dimensions: {dimensions}")
                return dimensions
            else:
                print("❌ No embedding data returned")
        elif response.status_code == 401:
            print("❌ API Key Invalid - Please check your SILICONFLOW_API_KEY")
            print("   Get a new key from: https://siliconflow.com/")
        else:
            print(f"❌ API Error: {response.status_code}")
            print(f"Response: {response.text}")
    
    except Exception as e:
        print(f"❌ Connection error: {e}")
    
    return None

def test_qdrant_connection():
    """Test Qdrant connection."""
    print("\nπŸ—„οΈ  Testing Qdrant Connection")
    print("=" * 35)
    
    
    qdrant_api_key= os.getenv('QDRANT_API_KEY', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.DHeUsIY234NwS-6cYDJec807Vdzbs1PHmBBU3_Jz9oo') 
    # QDRANT_URL=os.getenv('QDRANT_URL', 'https://50f53cc8-bbb0-4939-8254-8f025a577222.us-west-2-0.aws.cloud.qdrant.io:6333')

    # qdrant_api_key = ""
    qdrant_url= os.getenv('QDRANT_URL', 'http://localhost:6333')

    
    if not qdrant_url:
        print("❌ No Qdrant URL found")
        return False
    
    try:
        print(f"πŸ”— Connecting to: {qdrant_url}")
        client = QdrantClient(url=qdrant_url, api_key=qdrant_api_key)
        
        # Test connection
        collections = client.get_collections()
        print(f"βœ… Connected! Found {len(collections.collections)} collections")
        
        # Check manufacturing_docs collection
        collection_names = [col.name for col in collections.collections]
        if 'manufacturing_docs' in collection_names:
            collection_info = client.get_collection('manufacturing_docs')
            current_dim = collection_info.config.params.vectors.size
            points_count = collection_info.points_count
            print(f"πŸ“‹ Collection 'manufacturing_docs' exists:")
            print(f"   - Vector dimensions: {current_dim}")
            print(f"   - Points count: {points_count}")
            return current_dim
        else:
            print("ℹ️  Collection 'manufacturing_docs' doesn't exist yet")
            return 0
    
    except Exception as e:
        print(f"❌ Connection failed: {e}")
        return False

def fix_qdrant_collection(correct_dimensions):
    """Fix the Qdrant collection with correct dimensions."""
    print(f"\nπŸ”§ Fixing Qdrant Collection (Dimensions: {correct_dimensions})")
    print("=" * 60)
    
    qdrant_url = os.getenv('QDRANT_URL')
    qdrant_api_key = os.getenv('QDRANT_API_KEY')
    collection_name = 'manufacturing_docs'
    
    try:
        client = QdrantClient(url=qdrant_url, api_key=qdrant_api_key)
        
        # Check current collection
        collections = client.get_collections()
        collection_names = [col.name for col in collections.collections]
        
        if collection_name in collection_names:
            collection_info = client.get_collection(collection_name)
            current_dim = collection_info.config.params.vectors.size
            
            if current_dim == correct_dimensions:
                print(f"βœ… Collection already has correct dimensions ({correct_dimensions})")
                return True
            
            print(f"πŸ—‘οΈ  Deleting existing collection (wrong dimensions: {current_dim})...")
            client.delete_collection(collection_name)
        
        # Create new collection
        print(f"πŸ†• Creating collection with {correct_dimensions} dimensions...")
        client.create_collection(
            collection_name=collection_name,
            vectors_config=models.VectorParams(
                size=correct_dimensions,
                distance=models.Distance.COSINE
            )
        )
        
        # Create indexes
        print("πŸ” Creating payload indexes...")
        indexes = [
            ("document_id", models.KeywordIndexParams()),
            ("chunk_id", models.KeywordIndexParams()),
            ("page_number", models.IntegerIndexParams()),
            ("worksheet_name", models.KeywordIndexParams()),
        ]
        
        for field_name, field_schema in indexes:
            try:
                client.create_payload_index(
                    collection_name=collection_name,
                    field_name=field_name,
                    field_schema=field_schema
                )
            except Exception as e:
                print(f"⚠️  Index creation warning for {field_name}: {e}")
        
        print("βœ… Collection fixed successfully!")
        return True
    
    except Exception as e:
        print(f"❌ Failed to fix collection: {e}")
        return False

def update_gradio_demo():
    """Update the Gradio demo with correct vector dimensions."""
    print("\nπŸ“ Updating Gradio Demo")
    print("=" * 25)
    
    # Check if the demo file exists
    demo_files = [
        'fixed_gradio_demo.py',
        'fixed_gradio_file_handling.py',
        'gradio_demo.py'
    ]
    
    demo_file = None
    for file in demo_files:
        if os.path.exists(file):
            demo_file = file
            break
    
    if not demo_file:
        print("❌ No Gradio demo file found")
        print("Please create fixed_gradio_demo.py with the corrected code")
        return False
    
    try:
        # Read the file
        with open(demo_file, 'r') as f:
            content = f.read()
        
        # Update vector_size
        if "'vector_size': 1024," in content:
            content = content.replace("'vector_size': 1024,", "'vector_size': 4096,")
            print("βœ… Updated vector_size from 1024 to 4096")
        elif "'vector_size': 4096," in content:
            print("βœ… Vector size already correct (4096)")
        else:
            print("⚠️  Could not find vector_size in demo file")
        
        # Write back
        with open(demo_file, 'w') as f:
            f.write(content)
        
        print(f"βœ… Updated {demo_file}")
        return True
    
    except Exception as e:
        print(f"❌ Failed to update demo: {e}")
        return False

def create_quick_demo():
    """Create a quick working demo file."""
    print("\nπŸš€ Creating Quick Demo")
    print("=" * 22)
    
    demo_content = '''import gradio as gr
import os
from dotenv import load_dotenv
load_dotenv()

# Quick test demo
def test_apis():
    """Test API connections."""
    results = []
    
    # Test Groq
    groq_key = os.getenv('GROQ_API_KEY')
    results.append(f"Groq API Key: {'βœ… Set' if groq_key else '❌ Missing'}")
    
    # Test SiliconFlow
    sf_key = os.getenv('SILICONFLOW_API_KEY')
    results.append(f"SiliconFlow API Key: {'βœ… Set' if sf_key else '❌ Missing'}")
    
    # Test Qdrant
    qdrant_url = os.getenv('QDRANT_URL')
    results.append(f"Qdrant URL: {'βœ… Set' if qdrant_url else '❌ Missing'}")
    
    return "\\n".join(results)

# Create simple interface
with gr.Blocks(title="RAG System Test") as demo:
    gr.Markdown("# πŸ§ͺ RAG System API Test")
    
    test_btn = gr.Button("Test APIs")
    output = gr.Textbox(label="Results", lines=10)
    
    test_btn.click(test_apis, outputs=output)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)
'''
    
    with open('quick_test_demo.py', 'w') as f:
        f.write(demo_content)
    
    print("βœ… Created quick_test_demo.py")
    return True

def main():
    """Main fix function."""
    print("🏭 Manufacturing RAG Agent - Quick Fix")
    print("=" * 50)
    
    # Step 1: Check environment
    if not check_environment():
        print("\n❌ Environment issues found. Please fix your .env file first.")
        return
    
    # Step 2: Test SiliconFlow API and get dimensions
    dimensions = test_siliconflow_api()
    if not dimensions:
        print("\n❌ SiliconFlow API test failed. Please check your API key.")
        return
    
    # Step 3: Test Qdrant
    current_dim = test_qdrant_connection()
    if current_dim is False:
        print("\n❌ Qdrant connection failed. Please check your Qdrant configuration.")
        return
    
    # Step 4: Fix Qdrant collection if needed
    if current_dim != dimensions:
        print(f"\n⚠️  Collection needs fixing: {current_dim} β†’ {dimensions}")
        if fix_qdrant_collection(dimensions):
            print("βœ… Qdrant collection fixed!")
        else:
            print("❌ Failed to fix Qdrant collection")
            return
    
    # Step 5: Update demo file
    if update_gradio_demo():
        print("βœ… Demo file updated!")
    
    # Step 6: Create quick test demo
    create_quick_demo()
    
    print("\nπŸŽ‰ All fixes applied!")
    print("\nπŸ“‹ Next Steps:")
    print("1. Test APIs: python quick_test_demo.py")
    print("2. Run full demo: python fixed_gradio_demo.py")
    print("3. Upload documents and test questions")

if __name__ == "__main__":
    main()