amrithtech23 commited on
Commit
3774a36
·
verified ·
1 Parent(s): 65ad11b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +347 -0
app.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ India-GST Tax Assistant - Complete GST Knowledge Base
3
+ From basic concepts to expert litigation queries
4
+ """
5
+
6
+ import os
7
+ import json
8
+ import gradio as gr
9
+ from pathlib import Path
10
+ from typing import Tuple, List, Dict, Optional
11
+
12
+ # ===================== CONFIGURATION =====================
13
+ BASE_DIR = Path(__file__).resolve().parent
14
+ DATA_FILE = BASE_DIR / "gst_data.json"
15
+
16
+ # Load GST dataset
17
+ with open(DATA_FILE, 'r', encoding='utf-8') as f:
18
+ GST_DATA = json.load(f)
19
+
20
+ TERMS = GST_DATA["terms"]
21
+ CATEGORIES = GST_DATA["metadata"]["categories"]
22
+ DIFFICULTY_LEVELS = GST_DATA["metadata"]["difficulty_levels"]
23
+
24
+ # Create search indices
25
+ TERM_INDEX = {term["term"].lower(): term for term in TERMS}
26
+ QUERY_INDEX = []
27
+ for term in TERMS:
28
+ for pattern in term["query_patterns"]:
29
+ QUERY_INDEX.append((pattern.lower(), term))
30
+
31
+ # ===================== SEARCH FUNCTIONS =====================
32
+ def search_gst(query: str, difficulty: str = "all", category: str = "all") -> Tuple[bool, List[Dict]]:
33
+ """
34
+ Search GST terms based on query
35
+ Returns: (found, list_of_matching_terms)
36
+ """
37
+ if not query or not query.strip():
38
+ return False, []
39
+
40
+ query_lower = query.lower().strip()
41
+ matches = []
42
+
43
+ # Check exact term match first
44
+ if query_lower in TERM_INDEX:
45
+ term = TERM_INDEX[query_lower]
46
+ if (difficulty == "all" or term["difficulty"] == difficulty) and \
47
+ (category == "all" or term["category"] == category):
48
+ return True, [term]
49
+
50
+ # Check query patterns
51
+ for pattern, term in QUERY_INDEX:
52
+ if pattern in query_lower:
53
+ if (difficulty == "all" or term["difficulty"] == difficulty) and \
54
+ (category == "all" or term["category"] == category):
55
+ if term not in matches:
56
+ matches.append(term)
57
+
58
+ # Check term definitions
59
+ for term in TERMS:
60
+ if query_lower in term["definition"].lower():
61
+ if (difficulty == "all" or term["difficulty"] == difficulty) and \
62
+ (category == "all" or term["category"] == category):
63
+ if term not in matches:
64
+ matches.append(term)
65
+
66
+ # Limit to top 5 matches
67
+ matches = matches[:5]
68
+
69
+ return len(matches) > 0, matches
70
+
71
+ def format_term_response(term: Dict, include_tamil: bool = True) -> str:
72
+ """Format a single GST term response"""
73
+
74
+ response = f"""
75
+ ## 📘 {term['term']}
76
+
77
+ ### Definition
78
+ {term['definition']}
79
+
80
+ ### Example
81
+ {term['example']}
82
+
83
+ ### Category
84
+ **{term['category']}** | Difficulty: **{term['difficulty'].title()}**
85
+
86
+ ### Legal Reference
87
+ {term['legal_reference']}
88
+
89
+ ### Related Terms
90
+ {', '.join(term['related_terms'][:5])}
91
+ """
92
+
93
+ if include_tamil and "tamil_translation" in term:
94
+ response += f"""
95
+ ### தமிழில்
96
+ **{term['tamil_translation']}**
97
+ """
98
+
99
+ response += f"""
100
+ ---
101
+ *Source: GST Knowledge Base | ID: {term['id']}*
102
+ """
103
+ return response
104
+
105
+ def format_multiple_responses(terms: List[Dict], query: str) -> str:
106
+ """Format multiple matching terms"""
107
+
108
+ response = f"""
109
+ ## 🔍 Multiple GST Terms Found for "{query}"
110
+
111
+ Please specify which term you're interested in:
112
+ """
113
+
114
+ for i, term in enumerate(terms, 1):
115
+ response += f"""
116
+ ### {i}. {term['term']}
117
+ **Category:** {term['category']} | **Difficulty:** {term['difficulty'].title()}
118
+ *{term['definition'][:150]}...*
119
+ """
120
+
121
+ response += """
122
+ ---
123
+ *Type the exact term number or name for detailed information.*
124
+ """
125
+ return response
126
+
127
+ # ===================== UI FUNCTIONS =====================
128
+ def ask_gst(query: str, difficulty: str, category: str, language: str) -> str:
129
+ """Main function to handle GST queries"""
130
+
131
+ if not query:
132
+ return "Please enter your GST-related question."
133
+
134
+ found, matches = search_gst(query, difficulty, category)
135
+
136
+ if not found:
137
+ return f"""
138
+ ❌ No GST terms found matching "{query}".
139
+
140
+ ### 💡 Suggestions:
141
+ - Try using different keywords
142
+ - Check for spelling errors
143
+ - Use simpler terms (e.g., "gst" instead of "goods and services tax")
144
+ - Browse by category below
145
+
146
+ ### 📋 Available Categories:
147
+ {', '.join(CATEGORIES[:10])}...
148
+
149
+ ### Difficulty Levels:
150
+ - **basic**: For citizens and beginners
151
+ - **intermediate**: For business owners
152
+ - **expert**: For CAs and tax professionals
153
+ """
154
+
155
+ include_tamil = (language == "Tamil" or language == "Both")
156
+
157
+ if len(matches) == 1:
158
+ return format_term_response(matches[0], include_tamil)
159
+ else:
160
+ return format_multiple_responses(matches, query)
161
+
162
+ def get_term_by_id(term_id: str, include_tamil: bool = True) -> str:
163
+ """Get term by ID for direct access"""
164
+ for term in TERMS:
165
+ if term["id"] == term_id:
166
+ return format_term_response(term, include_tamil)
167
+ return "Term not found."
168
+
169
+ # ===================== GRADIO INTERFACE =====================
170
+ css = """
171
+ #col-left { margin: 0 auto; max-width: 300px; }
172
+ #col-mid { margin: 0 auto; max-width: 300px; }
173
+ #col-right { margin: 0 auto; max-width: 600px; }
174
+ .gst-header {
175
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
176
+ color: white;
177
+ padding: 20px;
178
+ border-radius: 10px;
179
+ margin-bottom: 20px;
180
+ }
181
+ .gst-card {
182
+ border: 1px solid #e0e0e0;
183
+ border-radius: 8px;
184
+ padding: 15px;
185
+ margin: 10px 0;
186
+ background: white;
187
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
188
+ }
189
+ .difficulty-badge {
190
+ display: inline-block;
191
+ padding: 3px 8px;
192
+ border-radius: 12px;
193
+ font-size: 12px;
194
+ font-weight: bold;
195
+ }
196
+ .basic { background: #4CAF50; color: white; }
197
+ .intermediate { background: #FF9800; color: white; }
198
+ .expert { background: #f44336; color: white; }
199
+ """
200
+
201
+ with gr.Blocks(css=css, title="India-GST Tax Assistant") as demo:
202
+ gr.HTML("""
203
+ <div class="gst-header">
204
+ <h1 style="text-align: center;">📊 India-GST Tax Assistant</h1>
205
+ <p style="text-align: center; font-size: 18px;">From basic concepts to expert litigation - All GST knowledge in one place</p>
206
+ <p style="text-align: center;">Based on official GST Act, Rules, and CBIC notifications</p>
207
+ </div>
208
+ """)
209
+
210
+ with gr.Row():
211
+ with gr.Column(scale=1):
212
+ gr.Markdown("""
213
+ ### 👥 For All Users
214
+
215
+ | Level | For |
216
+ |-------|-----|
217
+ | **Basic** | Citizens, Small Business |
218
+ | **Intermediate** | Business Owners, Accountants |
219
+ | **Expert** | CAs, Tax Litigators |
220
+
221
+ ### 📚 Categories
222
+ - Basic Concepts
223
+ - Registration
224
+ - Returns & Compliance
225
+ - Valuation
226
+ - Input Tax Credit
227
+ - Exports & Imports
228
+ - Litigation & Appeals
229
+ - Forms & Procedures
230
+ """)
231
+
232
+ with gr.Column(scale=2):
233
+ query = gr.Textbox(
234
+ label="Your GST Question",
235
+ placeholder="e.g., what is gst, itc rules, gstr-3b due date, appeal procedure, rcm on services...",
236
+ lines=3
237
+ )
238
+
239
+ with gr.Row():
240
+ difficulty = gr.Radio(
241
+ label="Difficulty Level",
242
+ choices=["all", "basic", "intermediate", "expert"],
243
+ value="all"
244
+ )
245
+
246
+ category = gr.Dropdown(
247
+ label="Category",
248
+ choices=["all"] + CATEGORIES,
249
+ value="all"
250
+ )
251
+
252
+ language = gr.Radio(
253
+ label="Language",
254
+ choices=["English", "Tamil", "Both"],
255
+ value="English"
256
+ )
257
+
258
+ submit_btn = gr.Button("🔍 Get GST Information", variant="primary", size="lg")
259
+
260
+ output = gr.Textbox(
261
+ label="GST Information",
262
+ lines=20,
263
+ interactive=False,
264
+ show_copy_button=True
265
+ )
266
+
267
+ submit_btn.click(
268
+ fn=ask_gst,
269
+ inputs=[query, difficulty, category, language],
270
+ outputs=output
271
+ )
272
+
273
+ query.submit(
274
+ fn=ask_gst,
275
+ inputs=[query, difficulty, category, language],
276
+ outputs=output
277
+ )
278
+
279
+ with gr.Row():
280
+ gr.Examples(
281
+ examples=[
282
+ ["what is gst", "all", "all", "English"],
283
+ ["itc meaning", "intermediate", "Input Tax Credit", "English"],
284
+ ["gstr-3b due date", "intermediate", "Returns", "English"],
285
+ ["appeal procedure", "expert", "Litigation & Appeals", "English"],
286
+ ["rcm on services", "intermediate", "Payment", "English"],
287
+ ["composition scheme", "basic", "Special Schemes", "English"],
288
+ ["e-way bill rules", "intermediate", "Compliance", "English"],
289
+ ["export refund", "expert", "Exports & Imports", "English"],
290
+ ["cgst full form", "basic", "Basic Concepts", "Tamil"],
291
+ ["வரி செலுத்துவோர்", "basic", "Registration", "Tamil"]
292
+ ],
293
+ inputs=[query, difficulty, category, language],
294
+ outputs=output,
295
+ fn=ask_gst,
296
+ cache_examples=False
297
+ )
298
+
299
+ gr.Markdown("""
300
+ ---
301
+ ### 📌 About This Assistant
302
+
303
+ | Feature | Description |
304
+ |---------|-------------|
305
+ | **Terms** | 250+ GST terms from basic to expert |
306
+ | **Categories** | 12 comprehensive categories |
307
+ | **Query Patterns** | 1000+ real user queries |
308
+ | **Tamil Support** | Key terms in Tamil language |
309
+ | **Legal References** | CGST Act sections, Rules, Notifications |
310
+
311
+ ### 🎯 Query Examples
312
+
313
+ **For Citizens:**
314
+ - "what is gst"
315
+ - "gst rate on restaurant"
316
+ - "how to get gst invoice"
317
+
318
+ **For Business:**
319
+ - "gst registration limit"
320
+ - "itc eligibility"
321
+ - "gstr-1 vs gstr-3b"
322
+ - "e-way bill generation"
323
+
324
+ **For CAs/Experts:**
325
+ - "itc reversal rule 42"
326
+ - "appeal procedure under section 107"
327
+ - "search and seizure provisions"
328
+ - "anti-profiteering cases"
329
+
330
+ ### ⚖️ Legal Disclaimer
331
+ This information is based on GST laws and notifications as available. For specific cases, please consult a qualified Chartered Accountant or GST practitioner.
332
+ """)
333
+
334
+ # ===================== LAUNCH =====================
335
+ if __name__ == "__main__":
336
+ print("=" * 60)
337
+ print("📊 India-GST Tax Assistant")
338
+ print("=" * 60)
339
+ print(f"✅ Loaded {len(TERMS)} GST terms")
340
+ print(f"✅ Categories: {len(CATEGORIES)}")
341
+ print(f"✅ Difficulty levels: basic, intermediate, expert")
342
+ print("=" * 60)
343
+ print("🚀 Starting application...")
344
+ print("=" * 60)
345
+
346
+ demo.queue()
347
+ demo.launch(server_name="0.0.0.0", server_port=7860)