gst2k6 / app.py
amrithtech23's picture
Upload app.py
3774a36 verified
"""
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)