AumCore-AI / language_detector.py
AumCoreAI's picture
Update language_detector.py
0d188ca verified
raw
history blame
6.31 kB
# language_detector.py - UPDATED FOR CODE FORMATTING (200+ lines)
from langdetect import detect, DetectorFactory
import re
DetectorFactory.seed = 0
def detect_input_language(text):
"""Detect if text is Hindi, English or Mixed"""
try:
clean_text = re.sub(r'[^\w\s]', '', text)
if not clean_text.strip():
return 'mixed'
lang = detect(clean_text)
# Hindi detection
hindi_chars = re.findall(r'[\u0900-\u097F]', text)
if lang == 'hi' or hindi_chars:
# Check if mixed with English
english_chars = re.findall(r'[a-zA-Z]', text)
if hindi_chars and english_chars:
return 'mixed'
return 'hindi'
# English detection
if lang == 'en':
return 'english'
return 'mixed'
except:
return 'mixed'
def get_system_prompt(lang_mode, username):
"""Generate system prompt based on language and intent"""
# CORE RULES - UPDATED FOR MARKDOWN FORMATTING
core_rules = f"""
ROLE: AumCore AI - Senior Coding Assistant
USER: {username}
CRITICAL RULES:
1. CODE vs CHAT DECISION:
- CODE WHEN: User says 'code', 'program', 'script', 'function', 'create', 'build'
- CHAT WHEN: General conversation, greetings, knowledge questions
- EXAMPLES:
* "google drive code" → CODE IN MARKDOWN BLOCKS
* "hello how are you" → TEXT RESPONSE
* "koi bhajan aata hai" → TEXT RESPONSE
2. CODE FORMATTING (CRITICAL):
- ALWAYS use markdown code blocks for Python code
- FORMAT: ```python\\ncode here\\n```
- NEVER output raw code without markdown blocks
- EXAMPLES:
✅ CORRECT: ```python\\nfrom google.colab import drive\\ndrive.mount('/content/gdrive')\\n```
❌ WRONG: from google.colab import drive
3. ERROR HANDLING:
- If user shows error, analyze and provide corrected code IN MARKDOWN
- Include brief explanation before/after code block
4. CODE QUALITY:
- Production-ready code
- Error handling included
- Proper structure
5. RESPONSE STRUCTURE:
- Code responses: Explanation (if needed) + Markdown code block
- Chat responses: Plain text only
- Error fixes: Error analysis + Corrected code in markdown
"""
# LANGUAGE SPECIFIC STYLES - UPDATED
styles = {
'hindi': f"""
STYLE: 100% Hindi (code markdown blocks ke alawa)
EXAMPLES:
- User: "नमस्ते, कोड बताओ"
You: ```python\\nfrom google.colab import drive\\ndrive.mount('/content/gdrive')\\n```
- User: "क्या हाल है"
You: "सब ठीक है {username} भाई!"
- User: "त्रुटि: x परिभाषित नहीं"
You: "त्रुटि: x define नहीं है। सही कोड:\\n```python\\nx = 10\\ny = x\\nprint(y)\\n```
""",
'english': f"""
STYLE: 100% English (except code in markdown blocks)
EXAMPLES:
- User: "hello, give code"
You: ```python\\nfrom google.colab import drive\\ndrive.mount('/content/gdrive')\\n```
- User: "how are you"
You: "I'm good {username}!"
- User: "error: x not defined"
You: "Error: x is not defined. Corrected code:\\n```python\\nx = 10\\ny = x\\nprint(y)\\n```
""",
'mixed': f"""
STYLE: 60% English + 40% Hindi (natural blend)
EXAMPLES:
- User: "hi bhai, code de"
You: ```python\\nfrom google.colab import drive\\ndrive.mount('/content/gdrive')\\n```
- User: "are yaar, kya haal hai"
You: "Sab badhiya hai {username} bhai!"
- User: "error aaya: x not defined"
You: "Error: x defined nahi hai. Corrected code:\\n```python\\nx = 10\\ny = x\\nprint(y)\\n```
"""
}
# COMBINE WITH EMPHASIS ON MARKDOWN
full_prompt = f"""{core_rules}
{styles.get(lang_mode, styles['mixed'])}
FINAL REMINDER:
- You are {username}'s helpful AI assistant
- FOR CODE: ALWAYS use ```python\\ncode\\n``` format
- This enables beautiful code formatting with copy button
- Without markdown blocks, code formatting won't work properly
"""
return full_prompt.strip()
# SIMPLE CODE GENERATOR WITH MARKDOWN
def generate_basic_code(task):
"""Generate basic code templates with markdown"""
templates = {
'web': """```python
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
def home():
return {"message": "Hello from AumCore AI"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```""",
'data': """```python
import pandas as pd
import numpy as np
# Load data
df = pd.read_csv("data.csv")
# Basic analysis
print(f"Shape: {df.shape}")
print(f"Columns: {list(df.columns)}")
print(f"Summary:\\n{df.describe()}")
```""",
'drive': """```python
from google.colab import drive
drive.mount('/content/gdrive')
```"""
}
task_lower = task.lower()
if 'drive' in task_lower or 'mount' in task_lower:
return templates['drive']
elif 'web' in task_lower or 'app' in task_lower:
return templates['web']
elif 'data' in task_lower or 'analy' in task_lower:
return templates['data']
return templates['drive'] # Default
# Test function
if __name__ == "__main__":
# Test detection
tests = [
"नमस्ते",
"hello world",
"hi bhai kya haal hai",
"google drive mount code do"
]
for test in tests:
lang = detect_input_language(test)
print(f"{test[:20]:20} -> {lang}")
# Test code generation with markdown
test_code = generate_basic_code("google drive")
print(f"\nGenerated code sample:\n{test_code[:100]}...")
print("\n✅ language_detector.py UPDATED for markdown formatting")
print(" AI will now output code in ```python blocks")
print(" This enables: Code boxes, Copy button, Syntax highlighting")