Spaces:
Running
Running
Update utils/functions.py
Browse files- utils/functions.py +55 -54
utils/functions.py
CHANGED
@@ -19,10 +19,12 @@ def init_fake_numbers_file():
|
|
19 |
with open(FAKE_NUMBERS_FILE, 'w') as f:
|
20 |
json.dump([], f)
|
21 |
else:
|
|
|
22 |
try:
|
23 |
with open(FAKE_NUMBERS_FILE, 'r') as f:
|
24 |
json.load(f)
|
25 |
except json.JSONDecodeError:
|
|
|
26 |
with open(FAKE_NUMBERS_FILE, 'w') as f:
|
27 |
json.dump([], f)
|
28 |
|
@@ -47,7 +49,7 @@ def add_fake_number(phone_number):
|
|
47 |
logging.error(f"Nie udało się zapisać numeru {phone_number}: {e}")
|
48 |
return False
|
49 |
else:
|
50 |
-
return False
|
51 |
|
52 |
# Sprawdzenie, czy numer telefonu jest w pliku JSON
|
53 |
def is_fake_number(phone_number):
|
@@ -74,34 +76,30 @@ def get_phone_info(phone_number):
|
|
74 |
# Proste sprawdzenia heurystyczne wiadomości
|
75 |
def simple_checks(message):
|
76 |
warnings = []
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
'
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
'
|
87 |
-
|
88 |
-
|
89 |
-
'payment confirmation']
|
90 |
-
}
|
91 |
-
|
92 |
-
for lang, keywords in scam_keywords.items():
|
93 |
-
if any(keyword in message.lower() for keyword in keywords):
|
94 |
-
warnings.append(f"Wiadomość zawiera słowa kluczowe związane z potencjalnym oszustwem ({lang}).")
|
95 |
|
|
|
|
|
|
|
96 |
if re.search(r'http[s]?://', message):
|
97 |
warnings.append("Wiadomość zawiera link.")
|
98 |
-
|
99 |
if re.search(r'\b(podaj|prześlij|udostępnij)\b.*\b(hasło|kod|dane osobowe|numer konta)\b', message.lower()):
|
100 |
warnings.append("Wiadomość zawiera prośbę o poufne informacje.")
|
101 |
-
|
102 |
return warnings
|
103 |
|
104 |
-
# Funkcja do analizy wiadomości za pomocą API SambaNova
|
105 |
def analyze_message(message, phone_number, additional_info, api_key, language):
|
106 |
if not api_key:
|
107 |
logging.error("Brak klucza API.")
|
@@ -111,82 +109,84 @@ def analyze_message(message, phone_number, additional_info, api_key, language):
|
|
111 |
headers = {
|
112 |
"Authorization": f"Bearer {api_key}"
|
113 |
}
|
114 |
-
|
115 |
-
#
|
116 |
system_prompts = {
|
117 |
'Polish': """
|
118 |
-
Jesteś zaawansowanym asystentem AI specjalizującym się w identyfikacji fałszywych wiadomości SMS. Twoim zadaniem jest przeprowadzenie szczegółowej analizy wiadomości
|
119 |
|
120 |
<analysis>
|
121 |
**Analiza Treści Wiadomości:**
|
122 |
-
-
|
123 |
-
-
|
124 |
-
-
|
125 |
</analysis>
|
126 |
|
127 |
<risk_assessment>
|
128 |
**Ocena Ryzyka Oszustwa:**
|
129 |
-
-
|
130 |
-
-
|
131 |
</risk_assessment>
|
132 |
|
133 |
<recommendations>
|
134 |
**Zalecenia dla Użytkownika:**
|
135 |
-
-
|
136 |
-
-
|
137 |
-
- Jeśli to możliwe,
|
138 |
</recommendations>
|
|
|
|
|
139 |
""",
|
140 |
'German': """
|
141 |
-
Du bist ein fortgeschrittener KI-Assistent, spezialisiert auf die Identifizierung gefälschter SMS-Nachrichten. Deine Aufgabe ist es, eine detaillierte Analyse der Nachricht durchzuführen
|
142 |
|
143 |
<analysis>
|
144 |
**Nachrichteninhaltsanalyse:**
|
145 |
-
-
|
146 |
-
-
|
147 |
-
-
|
148 |
</analysis>
|
149 |
|
150 |
<risk_assessment>
|
151 |
**Betrugsrisikobewertung:**
|
152 |
-
-
|
153 |
-
-
|
154 |
</risk_assessment>
|
155 |
|
156 |
<recommendations>
|
157 |
**Empfehlungen für den Benutzer:**
|
158 |
-
- Gib klare und konkrete
|
159 |
-
-
|
160 |
-
-
|
161 |
</recommendations>
|
162 |
""",
|
163 |
'English': """
|
164 |
-
You are an advanced AI assistant specializing in identifying fake SMS messages. Your task is to conduct a detailed analysis of the message,
|
165 |
|
166 |
<analysis>
|
167 |
**Message Content Analysis:**
|
168 |
-
-
|
169 |
-
-
|
170 |
-
-
|
171 |
</analysis>
|
172 |
|
173 |
<risk_assessment>
|
174 |
**Fraud Risk Assessment:**
|
175 |
-
-
|
176 |
-
-
|
177 |
</risk_assessment>
|
178 |
|
179 |
<recommendations>
|
180 |
**User Recommendations:**
|
181 |
-
- Provide clear and
|
182 |
-
-
|
183 |
-
- If possible,
|
184 |
</recommendations>
|
185 |
"""
|
186 |
}
|
187 |
-
|
188 |
system_prompt = system_prompts.get(language, system_prompts['English']) # Default to English if language not found
|
189 |
-
|
190 |
user_prompt = f"""Analyze the following message for potential fraud:
|
191 |
|
192 |
Message: "{message}"
|
@@ -214,6 +214,7 @@ Provide your analysis and conclusions following the guidelines above."""
|
|
214 |
if response.status_code == 200:
|
215 |
data = response.json()
|
216 |
ai_response = data['choices'][0]['message']['content']
|
|
|
217 |
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
218 |
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
219 |
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
@@ -295,7 +296,7 @@ def add_to_history(message, phone_number, analysis, risk, recommendations):
|
|
295 |
def get_history():
|
296 |
history_file = 'history.json'
|
297 |
try:
|
298 |
-
with open(history_file, 'r') as f:
|
299 |
history = json.load(f)
|
300 |
return history
|
301 |
except (json.JSONDecodeError, FileNotFoundError):
|
|
|
19 |
with open(FAKE_NUMBERS_FILE, 'w') as f:
|
20 |
json.dump([], f)
|
21 |
else:
|
22 |
+
# Sprawdzenie, czy plik nie jest pusty i zawiera prawidłowy JSON
|
23 |
try:
|
24 |
with open(FAKE_NUMBERS_FILE, 'r') as f:
|
25 |
json.load(f)
|
26 |
except json.JSONDecodeError:
|
27 |
+
# Jeśli plik jest uszkodzony lub pusty, zresetuj go do pustej listy
|
28 |
with open(FAKE_NUMBERS_FILE, 'w') as f:
|
29 |
json.dump([], f)
|
30 |
|
|
|
49 |
logging.error(f"Nie udało się zapisać numeru {phone_number}: {e}")
|
50 |
return False
|
51 |
else:
|
52 |
+
return False # Numer już istnieje
|
53 |
|
54 |
# Sprawdzenie, czy numer telefonu jest w pliku JSON
|
55 |
def is_fake_number(phone_number):
|
|
|
76 |
# Proste sprawdzenia heurystyczne wiadomości
|
77 |
def simple_checks(message):
|
78 |
warnings = []
|
79 |
+
# Rozbudowana baza słów kluczowych w trzech językach (polski, niemiecki, angielski)
|
80 |
+
scam_keywords = [
|
81 |
+
'pieniądze', 'przelew', 'hasło', 'kod', 'nagroda', 'wygrana', 'pilne', 'pomoc', 'opłata', 'konto', 'bank',
|
82 |
+
'spłata', 'dług', 'problem', 'uwaga', 'natychmiast', 'transakcja', 'podaj dane', 'cena', 'bonus', 'transakcja',
|
83 |
+
'alert', 'bezpieczeństwo', 'oszustwo', 'blokada', 'abonament', 'naliczenie', 'dług', 'monit', 'prośba',
|
84 |
+
'Überweisung', 'Passwort', 'Geld', 'dringend', 'Gewinn', 'Betrag', 'Schuld', 'Konto', 'Hilfe', 'Problem',
|
85 |
+
'Sofort', 'Transaktion', 'Daten angeben', 'Belohnung', 'Gewinnspiel', 'Bonus', 'Erinnerung', 'Warnung',
|
86 |
+
'sicher', 'Verdacht', 'blockiert', 'Zahlung', 'Zahlungsforderung', 'betrug', 'Bankkonto',
|
87 |
+
'Award', 'prize', 'account', 'urgent', 'money', 'transfer', 'help', 'password', 'code', 'payment',
|
88 |
+
'emergency', 'win', 'problem', 'immediate', 'transaction', 'bank account', 'debt', 'discount', 'offer',
|
89 |
+
'security', 'alert', 'fraud', 'blocked', 'subscription', 'charge', 'request', 'notice'
|
90 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
|
92 |
+
if any(keyword in message.lower() for keyword in scam_keywords):
|
93 |
+
warnings.append("Wiadomość zawiera słowa kluczowe związane z potencjalnym oszustwem.")
|
94 |
+
# Sprawdzenie obecności linków
|
95 |
if re.search(r'http[s]?://', message):
|
96 |
warnings.append("Wiadomość zawiera link.")
|
97 |
+
# Sprawdzenie, czy nadawca prosi o poufne informacje
|
98 |
if re.search(r'\b(podaj|prześlij|udostępnij)\b.*\b(hasło|kod|dane osobowe|numer konta)\b', message.lower()):
|
99 |
warnings.append("Wiadomość zawiera prośbę o poufne informacje.")
|
|
|
100 |
return warnings
|
101 |
|
102 |
+
# Funkcja do analizy wiadomości za pomocą API SambaNova
|
103 |
def analyze_message(message, phone_number, additional_info, api_key, language):
|
104 |
if not api_key:
|
105 |
logging.error("Brak klucza API.")
|
|
|
109 |
headers = {
|
110 |
"Authorization": f"Bearer {api_key}"
|
111 |
}
|
112 |
+
|
113 |
+
# Rozbudowane system prompts
|
114 |
system_prompts = {
|
115 |
'Polish': """
|
116 |
+
Jesteś zaawansowanym asystentem AI specjalizującym się w identyfikacji fałszywych wiadomości SMS. Twoim zadaniem jest przeprowadzenie szczegółowej, wieloetapowej analizy wiadomości. Twój system myślenia musi przechodzić przez każdą potencjalną czerwoną flagę, szczegółowo oceniać ryzyka i dostarczać złożoną, lecz czytelną analizę. Twoja odpowiedź powinna być podzielona na trzy sekcje:
|
117 |
|
118 |
<analysis>
|
119 |
**Analiza Treści Wiadomości:**
|
120 |
+
- Zidentyfikuj wszelkie potencjalne czerwone flagi, takie jak: błędy językowe, prośby o dane osobowe, pilne prośby o kontakt, sugestie dotyczące transferów finansowych itp.
|
121 |
+
- Ocen językowo-kulturowy kontekst wiadomości.
|
122 |
+
- Ocen wszelkie elementy, które mogą sugerować próbę wyłudzenia informacji lub pieniędzy.
|
123 |
</analysis>
|
124 |
|
125 |
<risk_assessment>
|
126 |
**Ocena Ryzyka Oszustwa:**
|
127 |
+
- Oceń prawdopodobieństwo, że wiadomość jest oszustwem na skali od 1 do 10.
|
128 |
+
- Zidentyfikuj i wyjaśnij czynniki, które wpływają na tę ocenę. Skoncentruj się na detalach, takich jak struktura wiadomości, użyte wyrażenia i kontekst.
|
129 |
</risk_assessment>
|
130 |
|
131 |
<recommendations>
|
132 |
**Zalecenia dla Użytkownika:**
|
133 |
+
- Przedstaw jasne i konkretne kroki, które użytkownik powinien podjąć.
|
134 |
+
- Zaproponuj opcje, takie jak blokowanie nadawcy, zgłoszenie wiadomości lub ignorowanie jej.
|
135 |
+
- Jeśli to możliwe, zaproponuj dodatkowe środki ostrożności, które użytkownik może podjąć, aby chronić swoje dane.
|
136 |
</recommendations>
|
137 |
+
|
138 |
+
Upewnij się, że każda sekcja jest wypełniona szczegółowo, przechodząc przez każdy potencjalny aspekt wiadomości.
|
139 |
""",
|
140 |
'German': """
|
141 |
+
Du bist ein fortgeschrittener KI-Assistent, spezialisiert auf die Identifizierung gefälschter SMS-Nachrichten. Deine Aufgabe ist es, eine detaillierte, schrittweise Analyse der Nachricht durchzuführen. Deine Antwort sollte in drei Abschnitte unterteilt sein:
|
142 |
|
143 |
<analysis>
|
144 |
**Nachrichteninhaltsanalyse:**
|
145 |
+
- Identifiziere potenzielle rote Flaggen wie: sprachliche Fehler, Anfragen nach persönlichen Daten, dringende Kontaktanfragen, Hinweise auf Finanztransaktionen.
|
146 |
+
- Berücksichtige den sprachlich-kulturellen Kontext der Nachricht.
|
147 |
+
- Bewerte alle Elemente, die auf einen Betrugsversuch hinweisen könnten.
|
148 |
</analysis>
|
149 |
|
150 |
<risk_assessment>
|
151 |
**Betrugsrisikobewertung:**
|
152 |
+
- Bewerte die Wahrscheinlichkeit, dass die Nachricht ein Betrug ist, auf einer Skala von 1 bis 10.
|
153 |
+
- Erläutere die Faktoren, die diese Bewertung beeinflussen, einschließlich der Struktur der Nachricht und der verwendeten Ausdrücke.
|
154 |
</risk_assessment>
|
155 |
|
156 |
<recommendations>
|
157 |
**Empfehlungen für den Benutzer:**
|
158 |
+
- Gib klare und konkrete Handlungsempfehlungen.
|
159 |
+
- Schlage Maßnahmen vor, wie das Blockieren des Absenders, das Melden der Nachricht oder das Ignorieren.
|
160 |
+
- Gib zusätzliche Sicherheitsvorkehrungen an, um persönliche und finanzielle Daten zu schützen.
|
161 |
</recommendations>
|
162 |
""",
|
163 |
'English': """
|
164 |
+
You are an advanced AI assistant specializing in identifying fake SMS messages. Your task is to conduct a detailed, step-by-step analysis of the message, using a deep thinking process. Your response should be divided into three sections:
|
165 |
|
166 |
<analysis>
|
167 |
**Message Content Analysis:**
|
168 |
+
- Identify potential red flags, such as: language errors, requests for personal information, urgent contact requests, suggestions of financial transfers, etc.
|
169 |
+
- Evaluate the linguistic and cultural context of the message.
|
170 |
+
- Assess any elements that may suggest an attempt to solicit information or money.
|
171 |
</analysis>
|
172 |
|
173 |
<risk_assessment>
|
174 |
**Fraud Risk Assessment:**
|
175 |
+
- Evaluate the likelihood that the message is fraudulent on a scale from 1 to 10.
|
176 |
+
- Identify and explain the factors that influence this assessment, focusing on message structure, expressions used, and context.
|
177 |
</risk_assessment>
|
178 |
|
179 |
<recommendations>
|
180 |
**User Recommendations:**
|
181 |
+
- Provide clear and specific actions the user should take.
|
182 |
+
- Suggest options like blocking the sender, reporting the message, or ignoring it.
|
183 |
+
- If possible, recommend additional precautions to protect the user’s personal and financial data.
|
184 |
</recommendations>
|
185 |
"""
|
186 |
}
|
187 |
+
|
188 |
system_prompt = system_prompts.get(language, system_prompts['English']) # Default to English if language not found
|
189 |
+
|
190 |
user_prompt = f"""Analyze the following message for potential fraud:
|
191 |
|
192 |
Message: "{message}"
|
|
|
214 |
if response.status_code == 200:
|
215 |
data = response.json()
|
216 |
ai_response = data['choices'][0]['message']['content']
|
217 |
+
# Parsowanie odpowiedzi
|
218 |
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
219 |
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
220 |
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
|
|
296 |
def get_history():
|
297 |
history_file = 'history.json'
|
298 |
try:
|
299 |
+
with open(history_file, 'r') as f):
|
300 |
history = json.load(f)
|
301 |
return history
|
302 |
except (json.JSONDecodeError, FileNotFoundError):
|