Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions app/router/analyze.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from fastapi import APIRouter
from app.dto.response import ApiResponse

# 문자 분석 전용 라우터 생성
router = APIRouter(prefix="/analyze", tags=["Analyze"])

@router.post("", response_model=ApiResponse[dict])
Expand All @@ -12,10 +13,10 @@ async def analyze_smishing(payload: dict):
dummy_result = {
"smishing_detected": False,
"url_analysis": {
"is_shortened": True,
"origin_url": "https://safe-destination.com",
"malicious_count": 0,
"is_shortened": True, # 단축 URL 여부
"origin_url": "https://safe-destination.com", # 최종 목적지 URL
"malicious_count": 0, # 악성 판전 횟수
"badge_color": "GREEN"
}
}
return ApiResponse.success(data=dummy_result, message="분석이 완료되었습니다.")
return ApiResponse.success(data=dummy_result, message="문자 및 URL 분석이 완료되었습니다.")
22 changes: 22 additions & 0 deletions app/router/analyze_voice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from fastapi import APIRouter
from app.dto.response import ApiResponse

# 음성 분석 전용 라우터 생성
router = APIRouter(prefix="/analyze-voice", tags=["Analyze Voice"])

@router.post("", response_model=ApiResponse[dict])
async def analyze_voice_call(payload: dict):
"""
스프링으로부터 음성 데이터 또는 STT 텍스트 정보를 받아
보이스피싱 및 악성 문맥 분석을 수행하는 엔드포인트 초안
"""

# 더미 결과 구조
dummy_result = {
"voice_phishing_detected": False,
"risk_score": 15, # 보이스피싱 위험도 점수
"detected_keywords": [], # 탐지된 금융 사기 관련 키워드 목록
"analysis_summary": "현재 통화 문맥상 금융 사기 및 피싱 징후가 발견되지 않은 안전한 상태입니다."
}

return ApiResponse.success(data=dummy_result, message="음성 분석이 완료되었습니다.")
27 changes: 27 additions & 0 deletions app/service/url/url_extractor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import re

# URL을 탐지하기 위한 정규표현식 패턴
URL_PATTERN = re.compile(r'https?://[^\s\'"<>]+')

def extract_urls_from_text(text: str) -> list[str]:
"""
텍스트 본문에서 모든 웹 URL 주소를 추출하고 중복을 제거하여 반환합니다.
"""

if not text:
return []

# 정규식 매칭
raw_urls = URL_PATTERN.findall(text)

# 문장 끝에 붙은 불필요한 문장부호 우측 정제
cleaned_urls = []

for url in raw_urls:
cleaned_url = url.rstrip('.,?!:;)[]')
cleaned_urls.append(cleaned_url)
Comment on lines +20 to +22

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve valid URL punctuation when trimming sentence punctuation.

rstrip('.,?!:;)[]') blindly removes valid trailing URL characters. For example, https://en.wikipedia.org/wiki/Foo_(bar) becomes https://en.wikipedia.org/wiki/Foo_(bar, which can make downstream URL analysis miss the original URL. Trim sentence punctuation only when it is clearly attached, and remove closing brackets only when they are unmatched.

🐛 Proposed fix
     for url in raw_urls:
-        cleaned_url = url.rstrip('.,?!:;)[]')
+        cleaned_url = url.rstrip(".,?!:;")
+        if cleaned_url.endswith(")") and cleaned_url.count(")") > cleaned_url.count("("):
+            cleaned_url = cleaned_url[:-1]
+        if cleaned_url.endswith("]") and cleaned_url.count("]") > cleaned_url.count("["):
+            cleaned_url = cleaned_url[:-1]
         cleaned_urls.append(cleaned_url)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for url in raw_urls:
cleaned_url = url.rstrip('.,?!:;)[]')
cleaned_urls.append(cleaned_url)
for url in raw_urls:
cleaned_url = url.rstrip(".,?!:;")
if cleaned_url.endswith(")") and cleaned_url.count(")") > cleaned_url.count("("):
cleaned_url = cleaned_url[:-1]
if cleaned_url.endswith("]") and cleaned_url.count("]") > cleaned_url.count("["):
cleaned_url = cleaned_url[:-1]
cleaned_urls.append(cleaned_url)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/service/url/url_extractor.py` around lines 20 - 22, Update the
URL-cleaning loop in the URL extraction function to trim sentence punctuation
only when it is clearly attached, preserving valid trailing URL characters.
Remove closing brackets such as “)” or “]” only when they are unmatched by
corresponding opening brackets in the URL, so balanced URL paths like
“Foo_(bar)” remain intact.


# 추출 순서를 보존하며 중복 제거
unique_urls = list(dict.fromkeys(cleaned_urls))

return unique_urls
36 changes: 36 additions & 0 deletions tests/test_url_extractor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import unittest
from app.service.url.url_extractor import extract_urls_from_text

class TestUrlExtractor(unittest.TestCase):

def test_no_url_text(self):
"""시나리오 1: URL이 아예 없는 순수 대화 텍스트 -> 빈 리스트 반환"""
text = "안녕하세요! 오늘 점심 뭐 드실래요? 맛있는 거 추천해주세요."
self.assertEqual(extract_urls_from_text(text), [])

def test_single_normal_url(self):
"""시나리오 2: 일반적인 URL이 포함된 문장 -> 정상 추출"""
text = "국민은행 보안 업데이트 링크입니다. https://www.kookminbank.com 확인해보세요."
expected = ["https://www.kookminbank.com"]
self.assertEqual(extract_urls_from_text(text), expected)

def test_multiple_urls(self):
"""시나리오 3: 한 문장에 서로 다른 URL이 2개 이상 포함된 문장 -> 모두 추출"""
text = "여기 구글 주소 https://google.com 이랑 네이버 주소 http://naver.com 보냅니다."
expected = ["https://google.com", "http://naver.com"]
self.assertEqual(extract_urls_from_text(text), expected)

def test_url_with_trailing_punctuation(self):
"""시나리오 4: 문장 맨 끝에 온점이나 기호와 함께 URL이 위치한 경우 -> 기호 제외하고 깔끔하게 추출 (억까 방지)"""
text = "아래 단축 링크를 꼭 클릭해주세요: https://bit.ly/3xyz."
expected = ["https://bit.ly/3xyz"]
self.assertEqual(extract_urls_from_text(text), expected)

def test_duplicate_urls(self):
"""시나리오 5: 동일한 URL이 반복되는 문장 -> 중복 제거되어 1개만 반환"""
text = "급합니다!! https://bit.ly/3xyz 빨리 확인하세요! 다시 보냅니다 https://bit.ly/3xyz"
expected = ["https://bit.ly/3xyz"]
self.assertEqual(extract_urls_from_text(text), expected)

if __name__ == '__main__':
unittest.main()