File size: 7,914 Bytes
9844436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a351
9844436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a351
9844436
 
 
 
 
 
 
 
 
5d0a351
 
 
9844436
 
 
 
5d0a351
9844436
 
5d0a351
 
9844436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a351
 
9844436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a351
 
 
9844436
5d0a351
 
9844436
5d0a351
9844436
5d0a351
 
9844436
5d0a351
 
 
 
 
 
 
9844436
 
 
 
 
5d0a351
 
 
9844436
 
 
 
 
 
 
 
 
 
 
5d0a351
9844436
5d0a351
9844436
 
 
 
 
 
5d0a351
9844436
 
 
 
 
 
 
 
 
 
 
 
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
import re
from typing import Dict, List, Any, Optional
from google import genai
from google.genai import types
from app.core.config import settings
import logging

logger = logging.getLogger(__name__)

class GeminiService:
    def __init__(self):
        self.client = None
        self._initialize_client()
    
    def _initialize_client(self):
        try:
            if settings.gemini_api_key:
                self.client = genai.Client(api_key=settings.gemini_api_key)
                logger.info("Gemini client initialized successfully")
            else:
                logger.warning("Gemini API key not provided")
        except Exception as e:
            logger.error(f"Failed to initialize Gemini client: {str(e)}")
    
    def generateSearchQueryFromCase(self, caseFacts: str, geminiModel=None, verbose: bool = False) -> str:
        if not self.client:
            raise ValueError("Gemini client not initialized")
        
        prompt = f"""
You are a legal assistant for a retrieval system based on Indian criminal law.

Given the case facts below, generate a **concise and focused search query** with **only the most relevant legal keywords**. These should include:

- Specific **IPC sections**
- Core **legal concepts** (e.g., "right of private defence", "criminal breach of trust")
- **Crime type** (e.g., "assault", "corruption")
- Any relevant **procedural issue** (e.g., "absence of intent", "lack of evidence")

Do **not** include:
- Full sentences
- Personal names
- Generic or vague words (e.g., "man", "incident", "case", "situation")

Keep the query under **20 words**. Separate terms by commas if needed. Optimize for legal document search.

Case Facts:
\"\"\"{caseFacts}\"\"\"

Return only the search query, no explanation or prefix:
"""
        
        try:
            response = self.client.models.generate_content(
                model=settings.gemini_model,
                contents=prompt
            )
            
            if response.text:
                query = response.text.replace("Search Query:", "").strip().strip('"').replace("\n", "")
            else:
                query = caseFacts[:50]  # Fallback
            
            if verbose:
                logger.info(f"Generated RAG Query: {query}")
            
            return query
        except Exception as e:
            logger.error(f"Error generating search query: {str(e)}")
            raise ValueError(f"Search query generation failed: {str(e)}")
    
    def buildGeminiPrompt(self, inputText: str, modelVerdict: str, confidence: float, 
                         support: Dict[str, List], query: Optional[str] = None) -> str:
        verdictOutcome = "a loss for the person" if modelVerdict.lower() == "guilty" else "in favor of the person"
        
        prompt = f"""You are a judge evaluating a legal dispute under Indian law.

### Case Facts:
{inputText}

### Initial Model Verdict:
{modelVerdict.upper()} (Confidence: {confidence * 100:.2f}%)
This verdict is interpreted as {verdictOutcome}.
"""
        
        if query:
            prompt += f"\n### Legal Query Used:\n{query}\n"
        
        prompt += "\n---\n\n### Legal References Retrieved:\n\n#### Constitution Articles (Top 5):\n"
        for i, art in enumerate(support.get("constitution", [])):
            prompt += f"- {i+1}. {str(art)}\n"
        
        prompt += "\n#### IPC Sections (Top 5):\n"
        for i, sec in enumerate(support.get("ipcSections", [])):
            prompt += f"- {i+1}. {str(sec)}\n"
        
        prompt += "\n#### IPC Case Law (Top 5):\n"
        for i, case in enumerate(support.get("ipcCase", [])):
            prompt += f"- {i+1}. {str(case)}\n"
        
        prompt += "\n#### Statutes (Top 5):\n"
        for i, stat in enumerate(support.get("statutes", [])):
            prompt += f"- {i+1}. {str(stat)}\n"
        
        prompt += "\n#### QA Texts (Top 5):\n"
        for i, qa in enumerate(support.get("qaTexts", [])):
            prompt += f"- {i+1}. {str(qa)}\n"
        
        prompt += "\n#### General Case Law (Top 5):\n"
        for i, gcase in enumerate(support.get("caseLaw", [])):
            prompt += f"- {i+1}. {str(gcase)}\n"
        
        prompt += f"""

---

### Instructions to the Judge (You):

1. Review the legal materials provided:
   - Identify which Constitution articles, IPC sections, statutes, and case laws are relevant to the facts.
   - Also note and explain which retrieved references are **not applicable** or irrelevant.

2. If relevant past cases appear in the retrieved materials, summarize them and analyze whether they support or contradict the model's verdict.

3. Using the above, assess the model's prediction:
   - If confidence is below 60%, you may revise or retain it.
   - If confidence is 60% or higher, retain unless clear legal grounds exist to challenge it.

4. Provide a thorough and formal legal explanation that:
   - Justifies the final decision using legal logic
   - Cites relevant IPCs, constitutional provisions, statutes, and precedents
   - Explains any reasoning for overriding the model's prediction, if applicable

5. Conclude with the following lines, formatted as shown:

Final Verdict: Guilty or Not Guilty
Verdict Changed: Yes or No

Respond in the tone of a formal Indian judge. Your explanation should reflect reasoning, neutrality, and respect for legal procedure.
"""
        return prompt
    
    def extractFinalVerdict(self, geminiOutput: str) -> tuple[Optional[str], str]:
        verdictMatch = re.search(r"final verdict\s*[:\-]\s*(guilty|not guilty)", geminiOutput, re.IGNORECASE)
        changedMatch = re.search(r"verdict changed\s*[:\-]\s*(yes|no)", geminiOutput, re.IGNORECASE)
        
        finalVerdict = verdictMatch.group(1).lower() if verdictMatch else None
        verdictChanged = "changed" if changedMatch and changedMatch.group(1).lower() == "yes" else "not changed"
        
        return finalVerdict, verdictChanged
    
    def evaluateCaseWithGemini(self, inputText: str, modelVerdict: str, confidence: float, 
                              retrieveFn, geminiQueryModel=None):
        try:
            if geminiQueryModel:
                support, searchQuery = retrieveFn.retrieveDualSupportChunks(inputText, self)
            else:
                support, _ = retrieveFn.retrieveSupportChunksParallel(inputText)
                searchQuery = inputText

            prompt = self.buildGeminiPrompt(inputText, modelVerdict, confidence, support, searchQuery)
            response = self.client.models.generate_content(
                model=settings.gemini_model,
                contents=prompt
            )
            geminiOutput = response.text if response.text else "No response from Gemini"

            finalVerdict, verdictChanged = self.extractFinalVerdict(geminiOutput)

            logs = {
                "inputText": inputText,
                "modelVerdict": modelVerdict,
                "confidence": confidence,
                "support": support,
                "promptToGemini": prompt,
                "geminiOutput": geminiOutput,
                "finalVerdictByGemini": finalVerdict,
                "verdictChanged": verdictChanged,
                "ragSearchQuery": searchQuery
            }

            return logs

        except Exception as e:
            return {
                "error": str(e),
                "inputText": inputText,
                "modelVerdict": modelVerdict,
                "confidence": confidence,
                "ragSearchQuery": None,
                "support": None,
                "promptToGemini": None,
                "geminiOutput": None,
                "finalVerdictByGemini": None,
                "verdictChanged": None
            }
    
    def is_configured(self) -> bool:
        return self.client is not None
    
    def is_healthy(self) -> bool:
        return self.is_configured()