File size: 10,830 Bytes
3774a36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
India-GST Tax Assistant - Complete GST Knowledge Base
From basic concepts to expert litigation queries
"""

import os
import json
import gradio as gr
from pathlib import Path
from typing import Tuple, List, Dict, Optional

# ===================== CONFIGURATION =====================
BASE_DIR = Path(__file__).resolve().parent
DATA_FILE = BASE_DIR / "gst_data.json"

# Load GST dataset
with open(DATA_FILE, 'r', encoding='utf-8') as f:
    GST_DATA = json.load(f)

TERMS = GST_DATA["terms"]
CATEGORIES = GST_DATA["metadata"]["categories"]
DIFFICULTY_LEVELS = GST_DATA["metadata"]["difficulty_levels"]

# Create search indices
TERM_INDEX = {term["term"].lower(): term for term in TERMS}
QUERY_INDEX = []
for term in TERMS:
    for pattern in term["query_patterns"]:
        QUERY_INDEX.append((pattern.lower(), term))

# ===================== SEARCH FUNCTIONS =====================
def search_gst(query: str, difficulty: str = "all", category: str = "all") -> Tuple[bool, List[Dict]]:
    """
    Search GST terms based on query
    Returns: (found, list_of_matching_terms)
    """
    if not query or not query.strip():
        return False, []
    
    query_lower = query.lower().strip()
    matches = []
    
    # Check exact term match first
    if query_lower in TERM_INDEX:
        term = TERM_INDEX[query_lower]
        if (difficulty == "all" or term["difficulty"] == difficulty) and \
           (category == "all" or term["category"] == category):
            return True, [term]
    
    # Check query patterns
    for pattern, term in QUERY_INDEX:
        if pattern in query_lower:
            if (difficulty == "all" or term["difficulty"] == difficulty) and \
               (category == "all" or term["category"] == category):
                if term not in matches:
                    matches.append(term)
    
    # Check term definitions
    for term in TERMS:
        if query_lower in term["definition"].lower():
            if (difficulty == "all" or term["difficulty"] == difficulty) and \
               (category == "all" or term["category"] == category):
                if term not in matches:
                    matches.append(term)
    
    # Limit to top 5 matches
    matches = matches[:5]
    
    return len(matches) > 0, matches

def format_term_response(term: Dict, include_tamil: bool = True) -> str:
    """Format a single GST term response"""
    
    response = f"""
## 📘 {term['term']}

### Definition
{term['definition']}

### Example
{term['example']}

### Category
**{term['category']}** | Difficulty: **{term['difficulty'].title()}**

### Legal Reference
{term['legal_reference']}

### Related Terms
{', '.join(term['related_terms'][:5])}
"""
    
    if include_tamil and "tamil_translation" in term:
        response += f"""
### தமிழில்
**{term['tamil_translation']}**
"""
    
    response += f"""
---
*Source: GST Knowledge Base | ID: {term['id']}*
"""
    return response

def format_multiple_responses(terms: List[Dict], query: str) -> str:
    """Format multiple matching terms"""
    
    response = f"""
## 🔍 Multiple GST Terms Found for "{query}"

Please specify which term you're interested in:
"""
    
    for i, term in enumerate(terms, 1):
        response += f"""
### {i}. {term['term']}
**Category:** {term['category']} | **Difficulty:** {term['difficulty'].title()}
*{term['definition'][:150]}...*
"""
    
    response += """
---
*Type the exact term number or name for detailed information.*
"""
    return response

# ===================== UI FUNCTIONS =====================
def ask_gst(query: str, difficulty: str, category: str, language: str) -> str:
    """Main function to handle GST queries"""
    
    if not query:
        return "Please enter your GST-related question."
    
    found, matches = search_gst(query, difficulty, category)
    
    if not found:
        return f"""
❌ No GST terms found matching "{query}".

### 💡 Suggestions:
- Try using different keywords
- Check for spelling errors
- Use simpler terms (e.g., "gst" instead of "goods and services tax")
- Browse by category below

### 📋 Available Categories:
{', '.join(CATEGORIES[:10])}...

### Difficulty Levels:
- **basic**: For citizens and beginners
- **intermediate**: For business owners
- **expert**: For CAs and tax professionals
"""
    
    include_tamil = (language == "Tamil" or language == "Both")
    
    if len(matches) == 1:
        return format_term_response(matches[0], include_tamil)
    else:
        return format_multiple_responses(matches, query)

def get_term_by_id(term_id: str, include_tamil: bool = True) -> str:
    """Get term by ID for direct access"""
    for term in TERMS:
        if term["id"] == term_id:
            return format_term_response(term, include_tamil)
    return "Term not found."

# ===================== GRADIO INTERFACE =====================
css = """
#col-left { margin: 0 auto; max-width: 300px; }
#col-mid { margin: 0 auto; max-width: 300px; }
#col-right { margin: 0 auto; max-width: 600px; }
.gst-header { 
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 20px;
}
.gst-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.difficulty-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: bold;
}
.basic { background: #4CAF50; color: white; }
.intermediate { background: #FF9800; color: white; }
.expert { background: #f44336; color: white; }
"""

with gr.Blocks(css=css, title="India-GST Tax Assistant") as demo:
    gr.HTML("""
    <div class="gst-header">
        <h1 style="text-align: center;">📊 India-GST Tax Assistant</h1>
        <p style="text-align: center; font-size: 18px;">From basic concepts to expert litigation - All GST knowledge in one place</p>
        <p style="text-align: center;">Based on official GST Act, Rules, and CBIC notifications</p>
    </div>
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("""
            ### 👥 For All Users
            
            | Level | For |
            |-------|-----|
            | **Basic** | Citizens, Small Business |
            | **Intermediate** | Business Owners, Accountants |
            | **Expert** | CAs, Tax Litigators |
            
            ### 📚 Categories
            - Basic Concepts
            - Registration
            - Returns & Compliance
            - Valuation
            - Input Tax Credit
            - Exports & Imports
            - Litigation & Appeals
            - Forms & Procedures
            """)
        
        with gr.Column(scale=2):
            query = gr.Textbox(
                label="Your GST Question",
                placeholder="e.g., what is gst, itc rules, gstr-3b due date, appeal procedure, rcm on services...",
                lines=3
            )
            
            with gr.Row():
                difficulty = gr.Radio(
                    label="Difficulty Level",
                    choices=["all", "basic", "intermediate", "expert"],
                    value="all"
                )
                
                category = gr.Dropdown(
                    label="Category",
                    choices=["all"] + CATEGORIES,
                    value="all"
                )
                
                language = gr.Radio(
                    label="Language",
                    choices=["English", "Tamil", "Both"],
                    value="English"
                )
            
            submit_btn = gr.Button("🔍 Get GST Information", variant="primary", size="lg")
            
            output = gr.Textbox(
                label="GST Information",
                lines=20,
                interactive=False,
                show_copy_button=True
            )
    
    submit_btn.click(
        fn=ask_gst,
        inputs=[query, difficulty, category, language],
        outputs=output
    )
    
    query.submit(
        fn=ask_gst,
        inputs=[query, difficulty, category, language],
        outputs=output
    )
    
    with gr.Row():
        gr.Examples(
            examples=[
                ["what is gst", "all", "all", "English"],
                ["itc meaning", "intermediate", "Input Tax Credit", "English"],
                ["gstr-3b due date", "intermediate", "Returns", "English"],
                ["appeal procedure", "expert", "Litigation & Appeals", "English"],
                ["rcm on services", "intermediate", "Payment", "English"],
                ["composition scheme", "basic", "Special Schemes", "English"],
                ["e-way bill rules", "intermediate", "Compliance", "English"],
                ["export refund", "expert", "Exports & Imports", "English"],
                ["cgst full form", "basic", "Basic Concepts", "Tamil"],
                ["வரி செலுத்துவோர்", "basic", "Registration", "Tamil"]
            ],
            inputs=[query, difficulty, category, language],
            outputs=output,
            fn=ask_gst,
            cache_examples=False
        )
    
    gr.Markdown("""
    ---
    ### 📌 About This Assistant
    
    | Feature | Description |
    |---------|-------------|
    | **Terms** | 250+ GST terms from basic to expert |
    | **Categories** | 12 comprehensive categories |
    | **Query Patterns** | 1000+ real user queries |
    | **Tamil Support** | Key terms in Tamil language |
    | **Legal References** | CGST Act sections, Rules, Notifications |
    
    ### 🎯 Query Examples
    
    **For Citizens:**
    - "what is gst"
    - "gst rate on restaurant"
    - "how to get gst invoice"
    
    **For Business:**
    - "gst registration limit"
    - "itc eligibility"
    - "gstr-1 vs gstr-3b"
    - "e-way bill generation"
    
    **For CAs/Experts:**
    - "itc reversal rule 42"
    - "appeal procedure under section 107"
    - "search and seizure provisions"
    - "anti-profiteering cases"
    
    ### ⚖️ Legal Disclaimer
    This information is based on GST laws and notifications as available. For specific cases, please consult a qualified Chartered Accountant or GST practitioner.
    """)

# ===================== LAUNCH =====================
if __name__ == "__main__":
    print("=" * 60)
    print("📊 India-GST Tax Assistant")
    print("=" * 60)
    print(f"✅ Loaded {len(TERMS)} GST terms")
    print(f"✅ Categories: {len(CATEGORIES)}")
    print(f"✅ Difficulty levels: basic, intermediate, expert")
    print("=" * 60)
    print("🚀 Starting application...")
    print("=" * 60)
    
    demo.queue()
    demo.launch(server_name="0.0.0.0", server_port=7860)