Create intent_detector.py
Browse files- app/utils/intent_detector.py +64 -0
app/utils/intent_detector.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Detect user intent from input — code analysis, question, or mixed."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def detect_intent(text: str) -> str:
|
| 7 |
+
"""
|
| 8 |
+
Classify input as:
|
| 9 |
+
- 'analyze' : user pasted code to be analyzed
|
| 10 |
+
- 'chat' : user asked a question or made a statement
|
| 11 |
+
- 'mixed' : question about specific code they also pasted
|
| 12 |
+
|
| 13 |
+
Returns one of: 'analyze', 'chat', 'mixed'
|
| 14 |
+
"""
|
| 15 |
+
stripped = text.strip()
|
| 16 |
+
|
| 17 |
+
# Strong code signals: indented blocks, common keywords at line start
|
| 18 |
+
code_patterns = [
|
| 19 |
+
r"^\s*(def |class |import |from |function |const |let |var |public |private |#include)",
|
| 20 |
+
r"^\s*(if |for |while |return |async |await |try:|except:|catch\s*\()",
|
| 21 |
+
r"[{}\[\]]\s*$", # lines ending with braces
|
| 22 |
+
r"^\s+\w+.*[:=]\s*\S", # indented assignments
|
| 23 |
+
r"(->|=>|::|===|!==|&&|\|\|)", # operators common in code
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
question_patterns = [
|
| 27 |
+
r"\?",
|
| 28 |
+
r"^(what|why|how|when|where|who|can you|could you|explain|describe|tell me|is there|are there|should i|help me)",
|
| 29 |
+
r"^(fix|debug|review|check|analyze|look at|improve)",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
lines = stripped.split("\n")
|
| 33 |
+
code_line_count = 0
|
| 34 |
+
for line in lines:
|
| 35 |
+
for pat in code_patterns:
|
| 36 |
+
if re.search(pat, line, re.IGNORECASE):
|
| 37 |
+
code_line_count += 1
|
| 38 |
+
break
|
| 39 |
+
|
| 40 |
+
code_ratio = code_line_count / max(len(lines), 1)
|
| 41 |
+
has_question = any(
|
| 42 |
+
re.search(pat, stripped, re.IGNORECASE | re.MULTILINE)
|
| 43 |
+
for pat in question_patterns
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Multi-line with mostly code lines → analyze
|
| 47 |
+
if len(lines) >= 3 and code_ratio >= 0.4:
|
| 48 |
+
if has_question:
|
| 49 |
+
return "mixed"
|
| 50 |
+
return "analyze"
|
| 51 |
+
|
| 52 |
+
# Single line or low code ratio with question → chat
|
| 53 |
+
if has_question:
|
| 54 |
+
return "chat"
|
| 55 |
+
|
| 56 |
+
# Short single line, no question → chat (treat as conversation)
|
| 57 |
+
if len(lines) == 1:
|
| 58 |
+
return "chat"
|
| 59 |
+
|
| 60 |
+
# Default: if there's meaningful code present
|
| 61 |
+
if code_ratio >= 0.25:
|
| 62 |
+
return "analyze"
|
| 63 |
+
|
| 64 |
+
return "chat"
|