rafaldembski commited on
Commit
7cdd828
·
verified ·
1 Parent(s): be734bb

Update utils/functions.py

Browse files
Files changed (1) hide show
  1. utils/functions.py +88 -86
utils/functions.py CHANGED
@@ -35,7 +35,7 @@ def load_json(file_path):
35
  """Ładuje dane z pliku JSON. Jeśli plik nie istnieje, zwraca pustą listę lub domyślny obiekt."""
36
  if not os.path.exists(file_path):
37
  if file_path.endswith('stats.json'):
38
- return {"total": 0, "fraud": 0, "safe": 0}
39
  else:
40
  return []
41
  with open(file_path, 'r', encoding='utf-8') as file:
@@ -45,7 +45,7 @@ def load_json(file_path):
45
  except json.JSONDecodeError:
46
  logging.error(f"Nie można załadować danych z {file_path}. Plik jest uszkodzony.")
47
  if file_path.endswith('stats.json'):
48
- return {"total": 0, "fraud": 0, "safe": 0}
49
  return []
50
 
51
  def save_json(file_path, data):
@@ -84,21 +84,18 @@ def get_fake_numbers():
84
  fake_numbers = load_json(FAKE_NUMBERS_FILE)
85
  return fake_numbers
86
 
87
- def add_to_history(content, sender_info, analysis_text, risk_text, recommendations_text):
88
  """
89
  Dodaje wpis do historii analiz w pliku history.json.
90
  """
91
  history = load_json(HISTORY_FILE)
92
  history.append({
93
- "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
94
- "type": "Analysis",
95
- "details": {
96
- "content": content,
97
- "sender_info": sender_info,
98
- "analysis": analysis_text,
99
- "risk_assessment": risk_text,
100
- "recommendations": recommendations_text
101
- }
102
  })
103
  save_json(HISTORY_FILE, history)
104
  logging.info(f"Dodano wpis do history.json dla nadawcy {sender_info}.")
@@ -111,18 +108,22 @@ def get_history():
111
  logging.info("Historia analiz została pobrana pomyślnie.")
112
  return history
113
 
 
 
 
 
 
 
114
  def update_stats(fraud_detected=False):
115
  """
116
  Aktualizuje statystyki analiz w pliku stats.json.
117
  """
118
  stats = load_json(STATS_FILE)
119
- stats["total"] += 1
120
  if fraud_detected:
121
- stats["fraud"] += 1
122
- else:
123
- stats["safe"] += 1
124
  save_json(STATS_FILE, stats)
125
- logging.info(f"Statystyki zostały zaktualizowane: Analiz {stats['total']}, Oszustw {stats['fraud']}.")
126
 
127
  def get_stats():
128
  """
@@ -190,79 +191,79 @@ def analyze_message(content, sender_info, additional_info, api_key, language):
190
 
191
  system_prompts = {
192
  'Polish': """
193
- Jesteś zaawansowanym asystentem AI specjalizującym się w identyfikacji fałszywych wiadomości. Twoim zadaniem jest przeprowadzenie szczegółowej analizy poniższej wiadomości, wykorzystując głęboki proces myślenia i dostarczając kompleksową ocenę. Twoja odpowiedź powinna być podzielona na trzy sekcje:
194
-
195
- <analysis>
196
- **Analiza Treści Wiadomości:**
197
- - 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.
198
- - Opisz kontekst językowy i kulturowy wiadomości.
199
- - Zidentyfikuj wszelkie elementy, które mogą sugerować, że wiadomość jest próbą wyłudzenia informacji lub pieniędzy.
200
- </analysis>
201
-
202
- <risk_assessment>
203
- **Ocena Ryzyka Oszustwa:**
204
- - 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.
205
- - Wyjaśnij, jakie czynniki wpływają na tę ocenę.
206
- </risk_assessment>
207
-
208
- <recommendations>
209
- **Zalecenia dla Użytkownika:**
210
- - Podaj jasne i konkretne zalecenia dotyczące dalszych kroków, które użytkownik powinien podjąć.
211
- - Uwzględnij sugestie dotyczące bezpieczeństwa, takie jak blokowanie nadawcy, zgłaszanie wiadomości do odpowiednich instytucji, czy też ignorowanie wiadomości.
212
- - 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.
213
- </recommendations>
214
-
215
- Twoja odpowiedź powinna być sformatowana dokładnie w powyższy sposób, używając znaczników <analysis>, <risk_assessment> i <recommendations>. Upewnij się, że każda sekcja jest wypełniona kompletnie i szczegółowo.
216
  """,
217
  'German': """
218
- Du bist ein fortgeschrittener KI-Assistent, spezialisiert auf die Identifizierung gefälschter Nachrichten. Deine Aufgabe ist es, eine detaillierte Analyse der folgenden Nachricht durchzuführen, indem du einen tiefgreifenden Denkprozess nutzt und eine umfassende Bewertung lieferst. Deine Antwort sollte in drei Abschnitte unterteilt sein:
219
-
220
- <analysis>
221
- **Nachrichteninhaltsanalyse:**
222
- - 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.
223
- - Beschreibe den sprachlichen und kulturellen Kontext der Nachricht.
224
- - Identifiziere alle Elemente, die darauf hindeuten könnten, dass die Nachricht ein Versuch ist, Informationen oder Geld zu erlangen.
225
- </analysis>
226
-
227
- <risk_assessment>
228
- **Betrugsrisikobewertung:**
229
- - 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.
230
- - Erkläre, welche Faktoren diese Bewertung beeinflussen.
231
- </risk_assessment>
232
-
233
- <recommendations>
234
- **Empfehlungen für den Benutzer:**
235
- - Gib klare und konkrete Empfehlungen zu den nächsten Schritten, die der Benutzer unternehmen sollte.
236
- - Berücksichtige Sicherheitsempfehlungen wie das Blockieren des Absenders, das Melden der Nachricht an entsprechende Behörden oder das Ignorieren der Nachricht.
237
- - Wenn möglich, schlage zusätzliche Vorsichtsmaßnahmen vor, die der Benutzer ergreifen kann, um seine persönlichen und finanziellen Daten zu schützen.
238
- </recommendations>
239
-
240
- Deine Antwort sollte genau nach den oben genannten Richtlinien formatiert sein und die Markierungen <analysis>, <risk_assessment> und <recommendations> verwenden. Stelle sicher, dass jeder Abschnitt vollständig und detailliert ausgefüllt ist.
241
  """,
242
  'English': """
243
- You are an advanced AI assistant specializing in identifying fake messages. Your task is to conduct a detailed analysis of the following message, utilizing a deep thinking process and providing a comprehensive assessment. Your response should be divided into three sections:
244
-
245
- <analysis>
246
- **Message Content Analysis:**
247
- - Conduct a detailed analysis of the message content, identifying potential red flags such as language errors, requests for personal information, urgent contact requests, etc.
248
- - Describe the linguistic and cultural context of the message.
249
- - Identify any elements that may suggest the message is an attempt to solicit information or money.
250
- </analysis>
251
-
252
- <risk_assessment>
253
- **Fraud Risk Assessment:**
254
- - 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.
255
- - Explain the factors that influence this assessment.
256
- </risk_assessment>
257
-
258
- <recommendations>
259
- **User Recommendations:**
260
- - Provide clear and concrete recommendations regarding the next steps the user should take.
261
- - Include security suggestions such as blocking the sender, reporting the message to appropriate authorities, or ignoring the message.
262
- - If possible, suggest additional precautionary measures the user can take to protect their personal and financial information.
263
- </recommendations>
264
-
265
- Your response should be formatted exactly as specified above, using the <analysis>, <risk_assessment>, and <recommendations> tags. Ensure that each section is thoroughly and comprehensively filled out.
266
  """
267
  }
268
 
@@ -360,3 +361,4 @@ def extract_text_from_image(image_file):
360
  except Exception as e:
361
  logging.error(f"Błąd podczas ekstrakcji tekstu z obrazu: {e}")
362
  return f"Błąd podczas ekstrakcji tekstu z obrazu: {e}"
 
 
35
  """Ładuje dane z pliku JSON. Jeśli plik nie istnieje, zwraca pustą listę lub domyślny obiekt."""
36
  if not os.path.exists(file_path):
37
  if file_path.endswith('stats.json'):
38
+ return {"total_analyses": 0, "total_frauds_detected": 0}
39
  else:
40
  return []
41
  with open(file_path, 'r', encoding='utf-8') as file:
 
45
  except json.JSONDecodeError:
46
  logging.error(f"Nie można załadować danych z {file_path}. Plik jest uszkodzony.")
47
  if file_path.endswith('stats.json'):
48
+ return {"total_analyses": 0, "total_frauds_detected": 0}
49
  return []
50
 
51
  def save_json(file_path, data):
 
84
  fake_numbers = load_json(FAKE_NUMBERS_FILE)
85
  return fake_numbers
86
 
87
+ def add_to_history(message, sender_info, analysis_text, risk_text, recommendations_text):
88
  """
89
  Dodaje wpis do historii analiz w pliku history.json.
90
  """
91
  history = load_json(HISTORY_FILE)
92
  history.append({
93
+ "timestamp": datetime.now().isoformat(),
94
+ "message": message,
95
+ "sender_info": sender_info,
96
+ "analysis": analysis_text,
97
+ "risk_assessment": risk_text,
98
+ "recommendations": recommendations_text
 
 
 
99
  })
100
  save_json(HISTORY_FILE, history)
101
  logging.info(f"Dodano wpis do history.json dla nadawcy {sender_info}.")
 
108
  logging.info("Historia analiz została pobrana pomyślnie.")
109
  return history
110
 
111
+ def get_analysis_history():
112
+ """
113
+ Alias funkcji get_history dla zgodności z innymi modułami.
114
+ """
115
+ return get_history()
116
+
117
  def update_stats(fraud_detected=False):
118
  """
119
  Aktualizuje statystyki analiz w pliku stats.json.
120
  """
121
  stats = load_json(STATS_FILE)
122
+ stats["total_analyses"] += 1
123
  if fraud_detected:
124
+ stats["total_frauds_detected"] += 1
 
 
125
  save_json(STATS_FILE, stats)
126
+ logging.info(f"Statystyki zostały zaktualizowane: Analiz {stats['total_analyses']}, Oszustw {stats['total_frauds_detected']}.")
127
 
128
  def get_stats():
129
  """
 
191
 
192
  system_prompts = {
193
  'Polish': """
194
+ Jesteś zaawansowanym asystentem AI specjalizującym się w identyfikacji fałszywych wiadomości. Twoim zadaniem jest przeprowadzenie szczegółowej analizy poniższej wiadomości, wykorzystując głęboki proces myślenia i dostarczając kompleksową ocenę. Twoja odpowiedź powinna być podzielona na trzy sekcje:
195
+
196
+ <analysis>
197
+ **Analiza Treści Wiadomości:**
198
+ - 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.
199
+ - Opisz kontekst językowy i kulturowy wiadomości.
200
+ - Zidentyfikuj wszelkie elementy, które mogą sugerować, że wiadomość jest próbą wyłudzenia informacji lub pieniędzy.
201
+ </analysis>
202
+
203
+ <risk_assessment>
204
+ **Ocena Ryzyka Oszustwa:**
205
+ - 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.
206
+ - Wyjaśnij, jakie czynniki wpływają na tę ocenę.
207
+ </risk_assessment>
208
+
209
+ <recommendations>
210
+ **Zalecenia dla Użytkownika:**
211
+ - Podaj jasne i konkretne zalecenia dotyczące dalszych kroków, które użytkownik powinien podjąć.
212
+ - Uwzględnij sugestie dotyczące bezpieczeństwa, takie jak blokowanie nadawcy, zgłaszanie wiadomości do odpowiednich instytucji, czy też ignorowanie wiadomości.
213
+ - 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.
214
+ </recommendations>
215
+
216
+ Twoja odpowiedź powinna być sformatowana dokładnie w powyższy sposób, używając znaczników <analysis>, <risk_assessment> i <recommendations>. Upewnij się, że każda sekcja jest wypełniona kompletnie i szczegółowo.
217
  """,
218
  'German': """
219
+ Du bist ein fortgeschrittener KI-Assistent, spezialisiert auf die Identifizierung gefälschter Nachrichten. Deine Aufgabe ist es, eine detaillierte Analyse der folgenden Nachricht durchzuführen, indem du einen tiefgreifenden Denkprozess nutzt und eine umfassende Bewertung lieferst. Deine Antwort sollte in drei Abschnitte unterteilt sein:
220
+
221
+ <analysis>
222
+ **Nachrichteninhaltsanalyse:**
223
+ - 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.
224
+ - Beschreibe den sprachlichen und kulturellen Kontext der Nachricht.
225
+ - Identifiziere alle Elemente, die darauf hindeuten könnten, dass die Nachricht ein Versuch ist, Informationen oder Geld zu erlangen.
226
+ </analysis>
227
+
228
+ <risk_assessment>
229
+ **Betrugsrisikobewertung:**
230
+ - 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.
231
+ - Erkläre, welche Faktoren diese Bewertung beeinflussen.
232
+ </risk_assessment>
233
+
234
+ <recommendations>
235
+ **Empfehlungen für den Benutzer:**
236
+ - Gib klare und konkrete Empfehlungen zu den nächsten Schritten, die der Benutzer unternehmen sollte.
237
+ - Berücksichtige Sicherheitsempfehlungen wie das Blockieren des Absenders, das Melden der Nachricht an entsprechende Behörden oder das Ignorieren der Nachricht.
238
+ - Wenn möglich, schlage zusätzliche Vorsichtsmaßnahmen vor, die der Benutzer ergreifen kann, um seine persönlichen und finanziellen Daten zu schützen.
239
+ </recommendations>
240
+
241
+ Deine Antwort sollte genau nach den oben genannten Richtlinien formatiert sein und die Markierungen <analysis>, <risk_assessment> und <recommendations> verwenden. Stelle sicher, dass jeder Abschnitt vollständig und detailliert ausgefüllt ist.
242
  """,
243
  'English': """
244
+ You are an advanced AI assistant specializing in identifying fake messages. Your task is to conduct a detailed analysis of the following message, utilizing a deep thinking process and providing a comprehensive assessment. Your response should be divided into three sections:
245
+
246
+ <analysis>
247
+ **Message Content Analysis:**
248
+ - Conduct a detailed analysis of the message content, identifying potential red flags such as language errors, requests for personal information, urgent contact requests, etc.
249
+ - Describe the linguistic and cultural context of the message.
250
+ - Identify any elements that may suggest the message is an attempt to solicit information or money.
251
+ </analysis>
252
+
253
+ <risk_assessment>
254
+ **Fraud Risk Assessment:**
255
+ - 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.
256
+ - Explain the factors that influence this assessment.
257
+ </risk_assessment>
258
+
259
+ <recommendations>
260
+ **User Recommendations:**
261
+ - Provide clear and concrete recommendations regarding the next steps the user should take.
262
+ - Include security suggestions such as blocking the sender, reporting the message to appropriate authorities, or ignoring the message.
263
+ - If possible, suggest additional precautionary measures the user can take to protect their personal and financial information.
264
+ </recommendations>
265
+
266
+ Your response should be formatted exactly as specified above, using the <analysis>, <risk_assessment>, and <recommendations> tags. Ensure that each section is thoroughly and comprehensively filled out.
267
  """
268
  }
269
 
 
361
  except Exception as e:
362
  logging.error(f"Błąd podczas ekstrakcji tekstu z obrazu: {e}")
363
  return f"Błąd podczas ekstrakcji tekstu z obrazu: {e}"
364
+