rafaldembski commited on
Commit
2c03919
·
verified ·
1 Parent(s): 0e6f84f

Update utils/functions.py

Browse files
Files changed (1) hide show
  1. 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
- scam_keywords = {
78
- 'Polish': ['pieniądze', 'przelew', 'hasło', 'kod', 'nagroda', 'wygrana', 'pilne', 'pomoc', 'opłata',
79
- 'płatność', 'transakcja', 'karta kredytowa', 'konto bankowe', 'login', 'weryfikacja', 'awaria',
80
- 'fałszywe', 'zapłać', 'prześlij', 'złóż wniosek', 'aktywuj', 'dostęp', 'zweryfikuj', 'proszę podać',
81
- 'debet', 'dłużnik', 'pożyczka', 'zwrot pieniędzy', 'potwierdzenie płatności'],
82
- 'German': ['geld', 'überweisung', 'passwort', 'code', 'gewinn', 'gewonnen', 'dringend', 'hilfe', 'zahlung',
83
- 'gebühr', 'zahlungsempfänger', 'kreditkarte', 'bankkonto', 'login', 'verifizierung', 'ausfall',
84
- 'fälschung', 'zahlen', 'übertragen', 'antrag einreichen', 'aktivieren', 'zugang', 'überprüfen',
85
- 'bitte angeben', 'schuldner', 'kredit', 'rückerstattung', 'zahlung bestätigen'],
86
- 'English': ['money', 'transfer', 'password', 'code', 'prize', 'won', 'urgent', 'help', 'payment', 'fee',
87
- 'transaction', 'credit card', 'bank account', 'login', 'verification', 'failure', 'fake', 'pay',
88
- 'send', 'apply', 'activate', 'access', 'verify', 'please provide', 'debt', 'loan', 'refund',
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 z zaawansowanym procesem myślowym
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
- # Zaktualizowane prompts z jeszcze bardziej szczegółową analizą
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, wykorzystując głęboki proces myślenia i dostarczając kompleksową ocenę. Twoja odpowiedź powinna być podzielona na trzy sekcje:
119
 
120
  <analysis>
121
  **Analiza Treści Wiadomości:**
122
- - Przeprowadź szczegółową analizę treści wiadomości, identyfikując potencjalne czerwone flagi, takie jak błędy językowe, prośby o dane osobowe, pilne prośby o kontakt itp.
123
- - Opisz kontekst językowy i kulturowy wiadomości.
124
- - Zidentyfikuj wszelkie elementy, które mogą sugerować, że wiadomość jest próbą wyłudzenia informacji lub pieniędzy.
125
  </analysis>
126
 
127
  <risk_assessment>
128
  **Ocena Ryzyka Oszustwa:**
129
- - Na podstawie analizy treści i dostępnych informacji oceń prawdopodobieństwo, że wiadomość jest oszustwem. Użyj skali od 1 do 10, gdzie 1 oznacza bardzo niskie ryzyko, a 10 bardzo wysokie ryzyko.
130
- - Wyjaśnij, jakie czynniki wpływają na tę ocenę.
131
  </risk_assessment>
132
 
133
  <recommendations>
134
  **Zalecenia dla Użytkownika:**
135
- - Podaj jasne i konkretne zalecenia dotyczące dalszych kroków, które użytkownik powinien podjąć.
136
- - Uwzględnij sugestie dotyczące bezpieczeństwa, takie jak blokowanie nadawcy, zgłaszanie wiadomości do odpowiednich instytucji, czy też ignorowanie wiadomości.
137
- - Jeśli to możliwe, zasugeruj dodatkowe środki ostrożności, które użytkownik może podjąć, aby chronić swoje dane osobowe i finansowe.
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, indem du einen tiefgreifenden Denkprozess nutzt und eine umfassende Bewertung lieferst. Deine Antwort sollte in drei Abschnitte unterteilt sein:
142
 
143
  <analysis>
144
  **Nachrichteninhaltsanalyse:**
145
- - Führe eine detaillierte Analyse des Nachrichteninhalts durch und identifiziere potenzielle rote Flaggen wie sprachliche Fehler, Aufforderungen zur Preisgabe persönlicher Daten, dringende Kontaktanfragen usw.
146
- - Beschreibe den sprachlichen und kulturellen Kontext der Nachricht.
147
- - Identifiziere alle Elemente, die darauf hindeuten könnten, dass die Nachricht ein Versuch ist, Informationen oder Geld zu erlangen.
148
  </analysis>
149
 
150
  <risk_assessment>
151
  **Betrugsrisikobewertung:**
152
- - Basierend auf der Inhaltsanalyse und den verfügbaren Informationen, bewerte die Wahrscheinlichkeit, dass die Nachricht ein Betrug ist. Verwende eine Skala von 1 bis 10, wobei 1 sehr geringes Risiko und 10 sehr hohes Risiko bedeutet.
153
- - Erkläre, welche Faktoren diese Bewertung beeinflussen.
154
  </risk_assessment>
155
 
156
  <recommendations>
157
  **Empfehlungen für den Benutzer:**
158
- - Gib klare und konkrete Empfehlungen zu den nächsten Schritten, die der Benutzer unternehmen sollte.
159
- - Berücksichtige Sicherheitsempfehlungen wie das Blockieren des Absenders, das Melden der Nachricht an entsprechende Behörden oder das Ignorieren der Nachricht.
160
- - Wenn möglich, schlage zusätzliche Vorsichtsmaßnahmen vor, die der Benutzer ergreifen kann, um seine persönlichen und finanziellen 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 analysis of the message, utilizing a deep thinking process and providing a comprehensive assessment. Your response should be divided into three sections:
165
 
166
  <analysis>
167
  **Message Content Analysis:**
168
- - Conduct a detailed analysis of the message content, identifying potential red flags such as language errors, requests for personal information, urgent contact requests, etc.
169
- - Describe the linguistic and cultural context of the message.
170
- - Identify any elements that may suggest the message is an attempt to solicit information or money.
171
  </analysis>
172
 
173
  <risk_assessment>
174
  **Fraud Risk Assessment:**
175
- - Based on the content analysis and available information, assess the likelihood that the message is fraudulent. Use a scale from 1 to 10, where 1 indicates very low risk and 10 indicates very high risk.
176
- - Explain the factors that influence this assessment.
177
  </risk_assessment>
178
 
179
  <recommendations>
180
  **User Recommendations:**
181
- - Provide clear and concrete recommendations regarding the next steps the user should take.
182
- - Include security suggestions such as blocking the sender, reporting the message to appropriate authorities, or ignoring the message.
183
- - If possible, suggest additional precautionary measures the user can take to protect their personal and financial information.
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):