File size: 28,536 Bytes
6c914fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
"""
ProVerBs Legal AI - Complete AI Integration
Features: 7 AI Modes + Rotating Logos + DeepSeek-OCR + ERNIE-4.5-VL + GDPVAL
"""

import gradio as gr
from huggingface_hub import InferenceClient
import json
import os
from datetime import datetime
from typing import Dict, List, Optional
import base64
from pathlib import Path

# AI Model Integration
try:
    from transformers import pipeline, AutoModel
    from datasets import load_dataset
    AI_MODELS_AVAILABLE = True
except ImportError:
    AI_MODELS_AVAILABLE = False
    print("⚠️ AI models not available. Install transformers and datasets.")

class EnhancedAILegalChatbot:
    """
    Enhanced AI Legal Chatbot with multiple AI models
    - DeepSeek-OCR for document text extraction
    - ERNIE-4.5-VL for vision-language understanding
    - OpenAI GDPVAL dataset for legal knowledge
    """
    
    def __init__(self):
        self.specialized_modes = {
            "navigation": "Application Navigation Guide",
            "general": "General Legal Assistant",
            "document_validation": "Document Validator with OCR & Vision AI",
            "legal_research": "Legal Research Assistant with GDPVAL",
            "etymology": "Legal Etymology Lookup",
            "case_management": "Case Management Helper",
            "regulatory_updates": "Regulatory Update Monitor"
        }
        
        # Initialize AI models
        self.ocr_pipeline = None
        self.vision_pipeline = None
        self.gdpval_dataset = None
        self.minimax_pipeline = None
        
        if AI_MODELS_AVAILABLE:
            self._initialize_models()
    
    def _initialize_models(self):
        """Initialize all AI models"""
        
        # DeepSeek-OCR for text extraction
        try:
            print("πŸ“¦ Loading DeepSeek-OCR...")
            self.ocr_pipeline = pipeline(
                "image-text-to-text", 
                model="deepseek-ai/DeepSeek-OCR", 
                trust_remote_code=True
            )
            print("βœ… DeepSeek-OCR loaded!")
        except Exception as e:
            print(f"⚠️ DeepSeek-OCR not loaded: {e}")
        
        # ERNIE-4.5-VL for vision-language understanding
        try:
            print("πŸ“¦ Loading ERNIE-4.5-VL (this may take a while)...")
            self.vision_pipeline = pipeline(
                "image-text-to-text",
                model="baidu/ERNIE-4.5-VL-28B-A3B-Thinking",
                trust_remote_code=True
            )
            print("βœ… ERNIE-4.5-VL loaded!")
        except Exception as e:
            print(f"⚠️ ERNIE-4.5-VL not loaded: {e}")
        
        # OpenAI GDPVAL dataset for legal knowledge
        try:
            print("πŸ“¦ Loading OpenAI GDPVAL dataset...")
            self.gdpval_dataset = load_dataset("openai/gdpval", split="train")
            print(f"βœ… GDPVAL loaded! {len(self.gdpval_dataset)} entries")
        except Exception as e:
            print(f"⚠️ GDPVAL not loaded: {e}")
        
        # MiniMax-M2 for advanced text generation
        try:
            print("πŸ“¦ Loading MiniMax-M2...")
            self.minimax_pipeline = pipeline(
                "text-generation",
                model="MiniMaxAI/MiniMax-M2",
                trust_remote_code=True
            )
            print("βœ… MiniMax-M2 loaded!")
        except Exception as e:
            print(f"⚠️ MiniMax-M2 not loaded: {e}")
    
    def process_with_ocr(self, image_path: str) -> str:
        """Extract text using DeepSeek-OCR"""
        if not self.ocr_pipeline:
            return "❌ OCR not available"
        
        try:
            result = self.ocr_pipeline(image_path)
            return result[0]['generated_text'] if result else ""
        except Exception as e:
            return f"❌ OCR error: {str(e)}"
    
    def process_with_vision(self, image_url: str, question: str) -> str:
        """Analyze image using ERNIE-4.5-VL"""
        if not self.vision_pipeline:
            return "❌ Vision AI not available"
        
        try:
            messages = [
                {
                    "role": "user",
                    "content": [
                        {"type": "image", "url": image_url},
                        {"type": "text", "text": question}
                    ]
                }
            ]
            result = self.vision_pipeline(text=messages)
            return result
        except Exception as e:
            return f"❌ Vision AI error: {str(e)}"
    
    def search_gdpval(self, query: str, limit: int = 5) -> str:
        """Search OpenAI GDPVAL dataset for legal knowledge"""
        if not self.gdpval_dataset:
            return "❌ GDPVAL dataset not available"
        
        try:
            # Simple keyword search (can be enhanced with embeddings)
            results = []
            query_lower = query.lower()
            
            for i, entry in enumerate(self.gdpval_dataset):
                if i >= 100:  # Limit search for performance
                    break
                
                # Check if query keywords appear in entry
                entry_text = str(entry).lower()
                if any(word in entry_text for word in query_lower.split()):
                    results.append(entry)
                    if len(results) >= limit:
                        break
            
            if results:
                formatted = "### πŸ“š GDPVAL Knowledge Base Results:\n\n"
                for i, result in enumerate(results, 1):
                    formatted += f"**Result {i}:**\n{result}\n\n"
                return formatted
            else:
                return "No relevant results found in GDPVAL dataset."
        except Exception as e:
            return f"❌ GDPVAL search error: {str(e)}"
    
    def analyze_legal_document(self, image_path: str) -> str:
        """
        Complete document analysis using multiple AI models:
        1. DeepSeek-OCR for text extraction
        2. ERNIE-4.5-VL for visual understanding
        3. Legal analysis with AI
        """
        analysis = "## πŸ“„ Complete Legal Document Analysis\n\n"
        
        # Step 1: OCR Text Extraction
        analysis += "### Step 1: Text Extraction (DeepSeek-OCR)\n"
        extracted_text = self.process_with_ocr(image_path)
        analysis += f"```\n{extracted_text[:500]}...\n```\n\n"
        
        # Step 2: Vision Analysis
        analysis += "### Step 2: Visual Document Understanding (ERNIE-4.5-VL)\n"
        vision_result = self.process_with_vision(
            image_path,
            "Analyze this legal document. Identify document type, key sections, and any notable elements."
        )
        analysis += f"{vision_result}\n\n"
        
        # Step 3: Legal Term Detection
        analysis += "### Step 3: Legal Analysis\n"
        legal_terms = self._detect_legal_terms(extracted_text)
        analysis += f"**Legal Terms Found:** {legal_terms}\n\n"
        
        # Step 4: Document Quality Check
        analysis += "### Step 4: Document Quality\n"
        quality = self._assess_document_quality(extracted_text)
        analysis += f"{quality}\n\n"
        
        return analysis
    
    def _detect_legal_terms(self, text: str) -> str:
        """Detect legal terminology in text"""
        legal_terms = [
            'contract', 'agreement', 'party', 'clause', 'provision',
            'whereas', 'hereby', 'herein', 'pursuant', 'consideration',
            'liability', 'indemnify', 'warranty', 'breach', 'terminate',
            'arbitration', 'jurisdiction', 'statute', 'regulation'
        ]
        
        found = [term for term in legal_terms if term.lower() in text.lower()]
        return ', '.join(found) if found else "None detected"
    
    def _assess_document_quality(self, text: str) -> str:
        """Assess document completeness and quality"""
        issues = []
        
        if len(text) < 100:
            issues.append("⚠️ Document seems very short")
        
        if not any(term in text.lower() for term in ['party', 'parties', 'agreement']):
            issues.append("⚠️ Missing party identification")
        
        if not any(term in text.lower() for term in ['date', 'dated', 'effective']):
            issues.append("⚠️ No effective date found")
        
        if issues:
            return "**Issues Found:**\n" + "\n".join(issues)
        else:
            return "βœ… Document appears complete"
    
    def generate_with_minimax(self, messages: list) -> str:
        """Generate response using MiniMax-M2"""
        if not self.minimax_pipeline:
            return "❌ MiniMax-M2 not available"
        
        try:
            result = self.minimax_pipeline(messages)
            return result[0]['generated_text'] if result else "No response"
        except Exception as e:
            return f"❌ MiniMax error: {str(e)}"
    
    def get_mode_system_prompt(self, mode: str) -> str:
        """Get specialized system prompt based on mode"""
        prompts = {
            "navigation": """You are a ProVerBs Application Navigation Guide.

**Enhanced Features:**
- Document Analysis with OCR (DeepSeek-OCR)
- Vision AI Analysis (ERNIE-4.5-VL)
- Legal Knowledge Base (OpenAI GDPVAL)
- 7 Specialized AI Modes

Guide users to the right features.""",
            
            "general": """You are a General Legal Assistant for ProVerBs Legal AI Platform. 
            
**Available Tools:**
- GDPVAL legal knowledge dataset
- Vision AI for document understanding
- OCR for text extraction

Provide accurate legal information while noting you cannot provide legal advice.""",
            
            "document_validation": """You are an Advanced Document Validator.

**AI-Powered Capabilities:**
- **DeepSeek-OCR**: Extract text from scanned documents
- **ERNIE-4.5-VL**: Understand document structure and layout visually
- **Legal Analysis**: Validate completeness and legal terms

**Process:**
1. Extract text with OCR
2. Analyze visually with ERNIE
3. Check legal validity
4. Provide detailed feedback""",
            
            "legal_research": """You are a Legal Research Assistant with GDPVAL access.

**Enhanced Research Tools:**
- OpenAI GDPVAL dataset for legal knowledge
- Case law and precedent search
- Statute and regulation analysis

Provide comprehensive research with citations.""",
            
            "etymology": """You are a Legal Etymology Expert. Explain origins of legal terms.""",
            
            "case_management": """You are a Case Management Helper with AI document processing.""",
            
            "regulatory_updates": """You are a Regulatory Update Monitor."""
        }
        return prompts.get(mode, prompts["general"])

def respond_with_mode(
    message,
    history: list,
    mode: str,
    model_choice: str,
    max_tokens: int,
    temperature: float,
    top_p: float,
):
    """Generate AI response based on selected mode"""
    chatbot = EnhancedAILegalChatbot()
    
    system_message = chatbot.get_mode_system_prompt(mode)
    
    # Enhanced responses for specific modes
    if mode == "document_validation" and "analyze" in message.lower():
        yield """
## πŸ“„ Advanced Document Validator

**Multi-AI Analysis Available:**

1. **DeepSeek-OCR**: Extract text from scanned documents
2. **ERNIE-4.5-VL**: Understand document structure visually
3. **Legal AI**: Validate and analyze content

**Upload a document to get:**
- βœ… Text extraction
- βœ… Visual structure analysis
- βœ… Legal term detection
- βœ… Completeness check
- βœ… Quality assessment
"""
        return
    
    if mode == "legal_research" and "search" in message.lower():
        # Search GDPVAL dataset
        gdpval_results = chatbot.search_gdpval(message)
        yield gdpval_results
        return
    
    # Choose AI model based on selection
    if model_choice == "MiniMax-M2" and chatbot.minimax_pipeline:
        # Use MiniMax-M2
        try:
            messages_minimax = [
                {"role": "system", "content": system_message},
                {"role": "user", "content": message}
            ]
            response = chatbot.generate_with_minimax(messages_minimax)
            yield response
        except Exception as e:
            yield f"MiniMax Error: {str(e)}"
    else:
        # Use HF Inference API (Llama) as default
        try:
            client = InferenceClient(model="meta-llama/Llama-3.3-70B-Instruct")
            
            messages = [{"role": "system", "content": system_message}]
            
            for user_msg, assistant_msg in history:
                if user_msg:
                    messages.append({"role": "user", "content": user_msg})
                if assistant_msg:
                    messages.append({"role": "assistant", "content": assistant_msg})
            
            messages.append({"role": "user", "content": message})
            
            response = ""
            for message_chunk in client.chat_completion(
                messages,
                max_tokens=max_tokens,
                stream=True,
                temperature=temperature,
                top_p=top_p,
            ):
                if message_chunk.choices and message_chunk.choices[0].delta.content:
                    token = message_chunk.choices[0].delta.content
                    response += token
                    yield response
        except Exception as e:
            # Provide demo response for local preview
            demo_response = f"""
## 🎯 Preview Mode Response

**Your Question:** {message}

**Mode:** {mode}

**Note:** This is a demo response for local preview. The AI chat will work fully once deployed to Hugging Face Spaces with authentication.

### What This Mode Does:

{system_message[:200]}...

### Features Available:
- βœ… UI and navigation fully functional
- βœ… All tabs working
- βœ… Watermark backgrounds active
- βœ… Logo rotation active
- ⚠️ AI responses require HF deployment

**To test AI chat:** Deploy to Hugging Face Spaces where authentication is automatic.

---

**For now:** Test the visual design, tab navigation, dropdowns, and timing features!
"""
            yield demo_response


# Custom CSS with watermark background logos
custom_css = """
.gradio-container {
    max-width: 1200px !important;
    position: relative;
}

/* Watermark background container */
.watermark-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;
    overflow: hidden;
}

/* Watermark logo styling */
.watermark-logo {
    position: absolute;
    width: 300px;
    height: 300px;
    opacity: 0.08;
    object-fit: contain;
    transition: opacity 2s ease-in-out;
}

.watermark-logo.active {
    opacity: 0.08;
}

.watermark-logo.hidden {
    opacity: 0;
}

/* Position watermarks at different locations */
.watermark-1 {
    top: 10%;
    left: 10%;
    transform: rotate(-15deg);
}

.watermark-2 {
    top: 15%;
    right: 15%;
    transform: rotate(20deg);
}

.watermark-3 {
    bottom: 20%;
    left: 15%;
    transform: rotate(10deg);
}

.watermark-4 {
    bottom: 15%;
    right: 10%;
    transform: rotate(-20deg);
}

.watermark-5 {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) rotate(-5deg);
}

/* Ensure content is above watermarks */
.gradio-container > * {
    position: relative;
    z-index: 1;
}

.header-section {
    text-align: center;
    padding: 40px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;
    margin-bottom: 30px;
    position: relative;
    z-index: 2;
}

.logo-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.rotating-logo {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid rgba(255, 255, 255, 0.8);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.header-section h1 {
    font-size: 3rem;
    margin-bottom: 10px;
    font-weight: 700;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

/* Make sure tabs and content are above watermarks */
.tabs, .tabitem {
    position: relative;
    z-index: 1;
}
"""

# JavaScript for rotating logos in header and random watermarks
rotating_logo_js = """
<script>
// Header logo rotation
function rotateHeaderLogo() {
    const logos = document.querySelectorAll('.rotating-logo');
    let currentIndex = 0;
    
    function showNextLogo() {
        logos.forEach((logo, index) => {
            logo.style.display = 'none';
        });
        if (logos.length > 0) {
            logos[currentIndex].style.display = 'block';
            currentIndex = (currentIndex + 1) % logos.length;
        }
    }
    
    showNextLogo();
    setInterval(showNextLogo, 60000);
}

// Random watermark rotation
function rotateWatermarks() {
    const watermarks = document.querySelectorAll('.watermark-logo');
    const logoImages = [
        'file/assets/logo_1.jpg',
        'file/assets/logo_2.jpg',
        'file/assets/logo_3.jpg'
    ];
    
    function randomizeWatermarks() {
        watermarks.forEach((watermark) => {
            // Fade out
            watermark.classList.remove('active');
            watermark.classList.add('hidden');
            
            setTimeout(() => {
                // Pick random logo
                const randomLogo = logoImages[Math.floor(Math.random() * logoImages.length)];
                watermark.src = randomLogo;
                
                // Fade in
                watermark.classList.remove('hidden');
                watermark.classList.add('active');
            }, 2000);
        });
    }
    
    // Initial randomization
    randomizeWatermarks();
    
    // Change watermarks every 30 seconds with random logos
    setInterval(randomizeWatermarks, 30000);
}

// Initialize both rotations
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        rotateHeaderLogo();
        rotateWatermarks();
    });
} else {
    rotateHeaderLogo();
    rotateWatermarks();
}
</script>
"""

# Create the main application
demo = gr.Blocks(title="ProVerBs Legal AI Platform")

with demo:
    
    # Watermark background logos
    gr.HTML(f"""
    <div class="watermark-container">
        <img src="file/assets/logo_1.jpg" class="watermark-logo watermark-1 active" alt="Watermark 1">
        <img src="file/assets/logo_2.jpg" class="watermark-logo watermark-2 active" alt="Watermark 2">
        <img src="file/assets/logo_3.jpg" class="watermark-logo watermark-3 active" alt="Watermark 3">
        <img src="file/assets/logo_1.jpg" class="watermark-logo watermark-4 active" alt="Watermark 4">
        <img src="file/assets/logo_2.jpg" class="watermark-logo watermark-5 active" alt="Watermark 5">
    </div>
    
    <style>{custom_css}</style>
    {rotating_logo_js}
    
    <!-- Header with Rotating Logos -->
    <div class="header-section">
        <div class="logo-container">
            <img src="file/assets/logo_1.jpg" class="rotating-logo" alt="Logo 1" style="display: block;">
            <img src="file/assets/logo_2.jpg" class="rotating-logo" alt="Logo 2" style="display: none;">
            <img src="file/assets/logo_3.jpg" class="rotating-logo" alt="Logo 3" style="display: none;">
        </div>
        <h1>βš–οΈ ProVerBs Legal AI Platform</h1>
        <p>Lawful vs. Legal: Dual Analysis "Adappt'plication"</p>
        <p style="font-size: 1rem; margin-top: 10px;">
            Multi-AI Legal System | 5 AI Models Working Together πŸš€
        </p>
    </div>
    """)
    
    gr.Markdown("---")
    
    # Main Tabs
    with gr.Tabs():
        
        # Tab 1: Welcome
        with gr.Tab("🏠 Welcome"):
            gr.Markdown("""
            ## Welcome to ProVerBs Legal AI Platform
            
            ### πŸ€– 5 AI Models Integrated:
            
            1. **DeepSeek-OCR** - Extract text from scanned documents
            2. **ERNIE-4.5-VL** - Advanced vision-language understanding
            3. **OpenAI GDPVAL** - Legal knowledge dataset
            4. **Meta Llama 3.3** - General AI assistance
            5. **MiniMax-M2** - Advanced text generation
            
            ### βš–οΈ 7 Specialized Modes:
            
            - πŸ“ Navigation Guide
            - πŸ’¬ General Legal Assistant (with GDPVAL)
            - πŸ“„ Document Validator (OCR + Vision AI)
            - πŸ” Legal Research (GDPVAL-powered)
            - πŸ“š Etymology Expert
            - πŸ’Ό Case Management
            - πŸ“‹ Regulatory Updates
            
            ### ✨ Unique Features:
            
            - **Multi-AI Document Analysis**: Combines OCR + Vision AI
            - **Legal Knowledge Base**: Access to GDPVAL dataset
            - **Rotating Custom Logos**: Your professional branding
            - **Complete Legal Solution**: All-in-one platform
            """)
        
        # Tab 2: AI Legal Chatbot
        with gr.Tab("πŸ€– AI Legal Chatbot"):
            gr.Markdown("""
            ## Multi-AI Legal Chatbot
            
            **Powered by 5 AI Models** for comprehensive legal assistance!
            
            **Choose Your AI Model:**
            - **Meta Llama 3.3** - Fast, efficient, streaming responses
            - **MiniMax-M2** - Advanced text generation capabilities
            """)
            
            mode_selector = gr.Dropdown(
                choices=[
                    "navigation",
                    "general",
                    "document_validation",
                    "legal_research",
                    "etymology",
                    "case_management",
                    "regulatory_updates"
                ],
                value="navigation",
                label="Select AI Assistant Mode"
            )
            
            model_selector = gr.Dropdown(
                choices=[
                    "Meta Llama 3.3",
                    "MiniMax-M2"
                ],
                value="Meta Llama 3.3",
                label="Select AI Model"
            )
            
            gr.Markdown("---")
            
            chatbot = gr.ChatInterface(
                respond_with_mode,
                chatbot=gr.Chatbot(height=500),
                additional_inputs=[
                    mode_selector,
                    model_selector,
                    gr.Slider(128, 4096, value=2048, label="Max Tokens"),
                    gr.Slider(0.1, 2.0, value=0.7, label="Temperature"),
                    gr.Slider(0.1, 1.0, value=0.95, label="Top-p"),
                ],
                examples=[
                    ["How do I use the multi-AI document analysis?"],
                    ["Search GDPVAL for contract law information"],
                    ["Analyze a document with vision AI"],
                ],
            )
        
        # Tab 3: Document Analysis (NEW!)
        with gr.Tab("πŸ“„ Document Analysis"):
            gr.Markdown("""
            ## πŸ“„ Document Upload & AI Analysis
            
            Upload legal documents for comprehensive AI analysis!
            """)
            
            with gr.Row():
                with gr.Column(scale=1):
                    doc_upload = gr.File(
                        label="πŸ“Ž Upload Document",
                        file_types=[".pdf", ".jpg", ".jpeg", ".png", ".txt"]
                    )
                    
                    analysis_type = gr.Radio(
                        choices=[
                            "Complete Analysis",
                            "OCR Only",
                            "Visual Only",
                            "Legal Validation"
                        ],
                        value="Complete Analysis",
                        label="Analysis Type"
                    )
                    
                    analyze_btn = gr.Button("πŸ” Analyze", variant="primary", size="lg")
                
                with gr.Column(scale=2):
                    analysis_output = gr.Markdown("Upload a document to begin analysis.")
            
            def analyze_doc(file_path, analysis_type):
                if not file_path:
                    return "⚠️ Please upload a document first."
                
                filename = file_path.split('/')[-1] if '/' in file_path else file_path.split('\\')[-1]
                
                return f"""
## πŸ“„ Document Analysis Results

**File:** {filename}  
**Analysis Type:** {analysis_type}

### ⚠️ Preview Mode

**What happens in production:**
- **DeepSeek-OCR** extracts text from images
- **ERNIE-4.5-VL** analyzes document structure
- **Legal AI** validates completeness

**Demo Output:**
- Document uploaded successfully βœ…
- File format supported βœ…
- Ready for AI analysis βœ…

**Note:** Full analysis available after HF deployment.

**Try it:** Upload any legal document (PDF, image, text) to see the interface!
"""
            
            analyze_btn.click(
                fn=analyze_doc,
                inputs=[doc_upload, analysis_type],
                outputs=analysis_output
            )
        
        # Tab 4: Features
        with gr.Tab("✨ Features"):
            gr.Markdown("""
            ## Advanced AI Features
            
            ### πŸ€– Integrated AI Models:
            
            1. **DeepSeek-OCR**
               - Text extraction from images
               - Document scanning
               - High accuracy OCR
            
            2. **ERNIE-4.5-VL** (Baidu)
               - Vision-language understanding
               - Document layout analysis
               - Visual question answering
            
            3. **OpenAI GDPVAL**
               - Legal knowledge dataset
               - Case law and precedents
               - Regulatory information
            
            4. **Meta Llama 3.3**
               - General AI assistance
               - Legal reasoning
               - Natural conversation
            
            5. **MiniMax-M2** ⭐ NEW!
               - Advanced text generation
               - High-quality responses
               - Alternative AI model option
            
            ### 🎯 What This Means:
            
            - **Most Advanced**: 5 AI models working together
            - **Best Analysis**: Multiple AI perspectives  
            - **Model Choice**: Select the best AI for your task
            - **Comprehensive**: Text + Vision + Knowledge
            - **Professional**: Your custom branding with logos
            """)
        
        # Tab 4: About
        with gr.Tab("ℹ️ About"):
            gr.Markdown("""
            ## About ProVerBs Legal AI - Complete Edition
            
            ### πŸš€ Version 2.1.0 - Complete Multi-AI Integration
            
            **This is the most advanced version** with all AI capabilities:
            
            - βœ… 7 Specialized AI Modes
            - βœ… 3 Rotating Custom Logos
            - βœ… DeepSeek-OCR Integration
            - βœ… ERNIE-4.5-VL Vision AI
            - βœ… OpenAI GDPVAL Dataset
            - βœ… Meta Llama 3.3 AI
            - βœ… MiniMax-M2 AI ⭐ NEW!
            
            ### πŸ“Š Technical Stack:
            
            - **Frontend**: Gradio 4.x
            - **OCR**: DeepSeek-OCR
            - **Vision**: ERNIE-4.5-VL-28B
            - **Dataset**: OpenAI GDPVAL
            - **LLM 1**: Meta Llama 3.3-70B
            - **LLM 2**: MiniMax-M2
            - **Platform**: Hugging Face Spaces
            
            ### ⚠️ Disclaimer:
            
            This platform provides general legal information only. 
            Always consult with a qualified attorney for specific legal matters.
            
            ---
            
            **Version 2.1.0** | Built by Solomon7890 | 5-Model AI Legal Platform
            """)
    
    # Footer
    gr.Markdown("""
    ---
    <div style="text-align: center; padding: 20px;">
        <p><strong>βš–οΈ ProVerBs Legal AI Platform</strong> | Version 2.1.0 - 5-Model AI Edition</p>
        <p>Powered by: DeepSeek-OCR β€’ ERNIE-4.5-VL β€’ GDPVAL β€’ Llama 3.3 β€’ MiniMax-M2</p>
        <p>Β© 2024 ProVerBs Legal AI</p>
    </div>
    """)

if __name__ == "__main__":
    demo.queue(max_size=20)
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )