Spaces:
Sleeping
Sleeping
rafaldembski
commited on
Commit
•
944b438
1
Parent(s):
3d3abb6
Update app.py
Browse files
app.py
CHANGED
@@ -1,218 +1,298 @@
|
|
1 |
-
import
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
simple_checks,
|
6 |
-
analyze_message,
|
7 |
-
init_stats_file,
|
8 |
-
update_stats,
|
9 |
-
add_to_history,
|
10 |
-
is_fake_number,
|
11 |
-
init_fake_numbers_file,
|
12 |
-
init_history_file
|
13 |
-
)
|
14 |
import os
|
|
|
|
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
page_title="📱 Detektor Fałszywych Wiadomości SMS",
|
19 |
-
page_icon="📱",
|
20 |
-
layout="wide"
|
21 |
-
)
|
22 |
-
|
23 |
-
# 2. Inicjalizacja plików
|
24 |
-
init_stats_file()
|
25 |
-
init_fake_numbers_file()
|
26 |
-
init_history_file()
|
27 |
-
|
28 |
-
# 3. Ukrycie bocznego menu Streamlit za pomocą CSS
|
29 |
-
hide_sidebar_style = """
|
30 |
-
<style>
|
31 |
-
/* Ukryj boczne menu */
|
32 |
-
[data-testid="stSidebar"] {
|
33 |
-
display: none;
|
34 |
-
}
|
35 |
-
</style>
|
36 |
-
"""
|
37 |
-
st.markdown(hide_sidebar_style, unsafe_allow_html=True)
|
38 |
-
|
39 |
-
# 4. Definiowanie tłumaczeń
|
40 |
-
translations = {
|
41 |
-
'Polish': {
|
42 |
-
'menu_analysis_sms': 'Analiza wiadomości',
|
43 |
-
'menu_about': 'O Projekcie',
|
44 |
-
'menu_education': 'Edukacja',
|
45 |
-
'menu_statistics': 'Statystyki',
|
46 |
-
'menu_contact': 'Kontakt',
|
47 |
-
'language_select': 'Wybierz język / Sprache auswählen / Select language',
|
48 |
-
'separator': '---',
|
49 |
-
'language_selected': 'Wybrany język: '
|
50 |
-
},
|
51 |
-
'German': {
|
52 |
-
'menu_analysis_sms': 'SMS-Analyse',
|
53 |
-
'menu_about': 'Über das Projekt',
|
54 |
-
'menu_education': 'Bildung',
|
55 |
-
'menu_statistics': 'Statistiken',
|
56 |
-
'menu_contact': 'Kontakt',
|
57 |
-
'language_select': 'Wybierz język / Sprache auswählen / Select language',
|
58 |
-
'separator': '---',
|
59 |
-
'language_selected': 'Ausgewählte Sprache: '
|
60 |
-
},
|
61 |
-
'English': {
|
62 |
-
'menu_analysis_sms': 'SMS Analysis',
|
63 |
-
'menu_about': 'About the Project',
|
64 |
-
'menu_education': 'Education',
|
65 |
-
'menu_statistics': 'Statistics',
|
66 |
-
'menu_contact': 'Contact',
|
67 |
-
'language_select': 'Wybierz język / Sprache auswählen / Select language',
|
68 |
-
'separator': '---',
|
69 |
-
'language_selected': 'Selected Language: '
|
70 |
-
}
|
71 |
-
}
|
72 |
-
|
73 |
-
# 5. Wybór języka z flagami w jednym wierszu
|
74 |
-
if 'language' not in st.session_state:
|
75 |
-
st.session_state.language = 'Polish'
|
76 |
-
|
77 |
-
# Nowy sposób na wybór języka bez użycia przycisków "POST"
|
78 |
-
selected_language = st.selectbox(
|
79 |
-
translations[st.session_state.language]['language_select'],
|
80 |
-
options=['Polish', 'German', 'English'],
|
81 |
-
index=['Polish', 'German', 'English'].index(st.session_state.language)
|
82 |
-
)
|
83 |
-
|
84 |
-
# Zapis wybranego języka w sesji
|
85 |
-
st.session_state.language = selected_language
|
86 |
-
|
87 |
-
st.markdown(f"**{translations[selected_language]['language_selected']} {selected_language}**")
|
88 |
-
|
89 |
-
# Dodanie separatora pod wyborem języka
|
90 |
-
st.markdown("---")
|
91 |
-
|
92 |
-
# 6. Pobranie przetłumaczonych opcji menu
|
93 |
-
menu_keys = ['menu_analysis_sms', 'menu_about', 'menu_education', 'menu_statistics', 'menu_contact']
|
94 |
-
menu_options = [translations[selected_language][key] for key in menu_keys]
|
95 |
-
|
96 |
-
# 7. Dodanie niestandardowego CSS do wzmocnienia stylów menu
|
97 |
-
custom_css = """
|
98 |
-
<style>
|
99 |
-
/* Stylizacja kontenera menu */
|
100 |
-
.streamlit-option-menu {
|
101 |
-
display: flex;
|
102 |
-
justify-content: center;
|
103 |
-
align-items: center;
|
104 |
-
padding: 10px 0;
|
105 |
-
margin-bottom: 10px;
|
106 |
-
}
|
107 |
|
108 |
-
|
109 |
-
|
110 |
-
background-color: #f0f0f0;
|
111 |
-
}
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
134 |
}
|
135 |
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
}
|
142 |
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
}
|
148 |
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
158 |
}
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import phonenumbers
|
2 |
+
from phonenumbers import geocoder, carrier
|
3 |
+
import re
|
4 |
+
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import os
|
6 |
+
import json
|
7 |
+
from datetime import datetime
|
8 |
+
import logging
|
9 |
|
10 |
+
# Konfiguracja logowania
|
11 |
+
logging.basicConfig(filename='app.log', level=logging.ERROR, format='%(asctime)s %(levelname)s:%(message)s')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
# Ścieżka do pliku JSON przechowującego fałszywe numery
|
14 |
+
FAKE_NUMBERS_FILE = 'fake_numbers.json'
|
|
|
|
|
15 |
|
16 |
+
# Inicjalizacja pliku JSON przechowującego fałszywe numery
|
17 |
+
def init_fake_numbers_file():
|
18 |
+
if not os.path.exists(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 |
+
# Jeśli plik jest uszkodzony lub pusty, zresetuj go do pustej listy
|
27 |
+
with open(FAKE_NUMBERS_FILE, 'w') as f:
|
28 |
+
json.dump([], f)
|
29 |
|
30 |
+
# Dodanie numeru telefonu do pliku JSON
|
31 |
+
def add_fake_number(phone_number):
|
32 |
+
try:
|
33 |
+
with open(FAKE_NUMBERS_FILE, 'r') as f:
|
34 |
+
fake_numbers = json.load(f)
|
35 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
36 |
+
fake_numbers = []
|
37 |
+
|
38 |
+
if not any(entry["phone_number"] == phone_number for entry in fake_numbers):
|
39 |
+
fake_numbers.append({
|
40 |
+
"phone_number": phone_number,
|
41 |
+
"reported_at": datetime.now().isoformat()
|
42 |
+
})
|
43 |
+
try:
|
44 |
+
with open(FAKE_NUMBERS_FILE, 'w') as f:
|
45 |
+
json.dump(fake_numbers, f, indent=4)
|
46 |
+
return True
|
47 |
+
except Exception as e:
|
48 |
+
logging.error(f"Nie udało się zapisać numeru {phone_number}: {e}")
|
49 |
+
return False
|
50 |
+
else:
|
51 |
+
return False # Numer już istnieje
|
52 |
+
|
53 |
+
# Sprawdzenie, czy numer telefonu jest w pliku JSON
|
54 |
+
def is_fake_number(phone_number):
|
55 |
+
try:
|
56 |
+
with open(FAKE_NUMBERS_FILE, 'r') as f:
|
57 |
+
fake_numbers = json.load(f)
|
58 |
+
return any(entry["phone_number"] == phone_number for entry in fake_numbers)
|
59 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
60 |
+
return False
|
61 |
+
|
62 |
+
# Funkcja do weryfikacji numeru telefonu
|
63 |
+
def get_phone_info(phone_number):
|
64 |
+
try:
|
65 |
+
parsed_number = phonenumbers.parse(phone_number, None)
|
66 |
+
country = geocoder.description_for_number(parsed_number, 'pl')
|
67 |
+
operator = carrier.name_for_number(parsed_number, 'pl')
|
68 |
+
return country, operator
|
69 |
+
except phonenumbers.NumberParseException:
|
70 |
+
return None, None
|
71 |
|
72 |
+
# Proste sprawdzenia heurystyczne wiadomości
|
73 |
+
def simple_checks(message, language):
|
74 |
+
warnings = []
|
75 |
+
# Baza słów kluczowych (polski, niemiecki, angielski)
|
76 |
+
scam_keywords = {
|
77 |
+
'Polish': ['pieniądze', 'przelew', 'hasło', 'kod', 'nagroda', 'wygrana', 'pilne', 'pomoc', 'opłata', 'bank', 'karta', 'konto', 'logowanie', 'transakcja', 'weryfikacja', 'dane osobowe', 'szybka płatność', 'blokada konta', 'powiadomienie'],
|
78 |
+
'German': ['Geld', 'Überweisung', 'Passwort', 'Code', 'Preis', 'Gewinn', 'dringend', 'Hilfe', 'Gebühr', 'Bank', 'Karte', 'Konto', 'Anmeldung', 'Transaktion', 'Verifizierung', 'persönliche Daten', 'schnelle Zahlung', 'Kontosperrung', 'Benachrichtigung'],
|
79 |
+
'English': ['money', 'transfer', 'password', 'code', 'prize', 'win', 'urgent', 'help', 'fee', 'bank', 'card', 'account', 'login', 'transaction', 'verification', 'personal information', 'quick payment', 'account lock', 'notification']
|
80 |
}
|
81 |
|
82 |
+
selected_keywords = scam_keywords.get(language, scam_keywords['English'])
|
83 |
+
|
84 |
+
if any(keyword in message.lower() for keyword in selected_keywords):
|
85 |
+
warnings.append("Wiadomość zawiera słowa kluczowe związane z potencjalnym oszustwem.")
|
86 |
+
if re.search(r'http[s]?://', message):
|
87 |
+
warnings.append("Wiadomość zawiera link.")
|
88 |
+
if re.search(r'\b(podaj|prześlij|udostępnij)\b.*\b(hasło|kod|dane osobowe|numer konta)\b', message.lower()):
|
89 |
+
warnings.append("Wiadomość zawiera prośbę o poufne informacje.")
|
90 |
+
return warnings
|
91 |
+
|
92 |
+
# Funkcja do analizy wiadomości za pomocą API SambaNova
|
93 |
+
def analyze_message(message, phone_number, additional_info, api_key, language):
|
94 |
+
if not api_key:
|
95 |
+
logging.error("Brak klucza API.")
|
96 |
+
return "Brak klucza API.", "Brak klucza API.", "Brak klucza API."
|
97 |
+
|
98 |
+
url = "https://api.sambanova.ai/v1/chat/completions"
|
99 |
+
headers = {
|
100 |
+
"Authorization": f"Bearer {api_key}"
|
101 |
}
|
102 |
|
103 |
+
# System prompts w trzech językach
|
104 |
+
system_prompts = {
|
105 |
+
'Polish': """
|
106 |
+
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:
|
107 |
+
|
108 |
+
<analysis>
|
109 |
+
**Analiza Treści Wiadomości:**
|
110 |
+
- 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.
|
111 |
+
- Opisz kontekst językowy i kulturowy wiadomości.
|
112 |
+
- Zidentyfikuj wszelkie elementy, które mogą sugerować, że wiadomość jest próbą wyłudzenia informacji lub pieniędzy.
|
113 |
+
</analysis>
|
114 |
+
|
115 |
+
<risk_assessment>
|
116 |
+
**Ocena Ryzyka Oszustwa:**
|
117 |
+
- 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.
|
118 |
+
- Wyjaśnij, jakie czynniki wpływają na tę ocenę.
|
119 |
+
</risk_assessment>
|
120 |
+
|
121 |
+
<recommendations>
|
122 |
+
**Zalecenia dla Użytkownika:**
|
123 |
+
- Podaj jasne i konkretne zalecenia dotyczące dalszych kroków, które użytkownik powinien podjąć.
|
124 |
+
- Uwzględnij sugestie dotyczące bezpieczeństwa, takie jak blokowanie nadawcy, zgłaszanie wiadomości do odpowiednich instytucji, czy też ignorowanie wiadomości.
|
125 |
+
- 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.
|
126 |
+
</recommendations>
|
127 |
+
|
128 |
+
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.
|
129 |
+
""",
|
130 |
+
'German': """
|
131 |
+
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:
|
132 |
+
|
133 |
+
<analysis>
|
134 |
+
**Nachrichteninhaltsanalyse:**
|
135 |
+
- 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.
|
136 |
+
- Beschreibe den sprachlichen und kulturellen Kontext der Nachricht.
|
137 |
+
- Identifiziere alle Elemente, die darauf hindeuten könnten, dass die Nachricht ein Versuch ist, Informationen oder Geld zu erlangen.
|
138 |
+
</analysis>
|
139 |
+
|
140 |
+
<risk_assessment>
|
141 |
+
**Betrugsrisikobewertung:**
|
142 |
+
- 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.
|
143 |
+
- Erkläre, welche Faktoren diese Bewertung beeinflussen.
|
144 |
+
</risk_assessment>
|
145 |
+
|
146 |
+
<recommendations>
|
147 |
+
**Empfehlungen für den Benutzer:**
|
148 |
+
- Gib klare und konkrete Empfehlungen zu den nächsten Schritten, die der Benutzer unternehmen sollte.
|
149 |
+
- Berücksichtige Sicherheitsempfehlungen wie das Blockieren des Absenders, das Melden der Nachricht an entsprechende Behörden oder das Ignorieren der Nachricht.
|
150 |
+
- Wenn möglich, schlage zusätzliche Vorsichtsmaßnahmen vor, die der Benutzer ergreifen kann, um seine persönlichen und finanziellen Daten zu schützen.
|
151 |
+
</recommendations>
|
152 |
+
|
153 |
+
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.
|
154 |
+
""",
|
155 |
+
'English': """
|
156 |
+
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:
|
157 |
+
|
158 |
+
<analysis>
|
159 |
+
**Message Content Analysis:**
|
160 |
+
- Conduct a detailed analysis of the message content, identifying potential red flags such as language errors, requests for personal information, urgent contact requests, etc.
|
161 |
+
- Describe the linguistic and cultural context of the message.
|
162 |
+
- Identify any elements that may suggest the message is an attempt to solicit information or money.
|
163 |
+
</analysis>
|
164 |
+
|
165 |
+
<risk_assessment>
|
166 |
+
**Fraud Risk Assessment:**
|
167 |
+
- 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.
|
168 |
+
- Explain the factors that influence this assessment.
|
169 |
+
</risk_assessment>
|
170 |
+
|
171 |
+
<recommendations>
|
172 |
+
**User Recommendations:**
|
173 |
+
- Provide clear and concrete recommendations regarding the next steps the user should take.
|
174 |
+
- Include security suggestions such as blocking the sender, reporting the message to appropriate authorities, or ignoring the message.
|
175 |
+
- If possible, suggest additional precautionary measures the user can take to protect their personal and financial information.
|
176 |
+
</recommendations>
|
177 |
+
|
178 |
+
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.
|
179 |
+
"""
|
180 |
}
|
181 |
|
182 |
+
system_prompt = system_prompts.get(language, system_prompts['English']) # Default to English if language not found
|
183 |
+
|
184 |
+
user_prompt = f"""Analyze the following message for potential fraud:
|
185 |
+
|
186 |
+
Message: "{message}"
|
187 |
+
Sender's Phone Number: "{phone_number}"
|
188 |
+
|
189 |
+
Additional Information:
|
190 |
+
{additional_info}
|
191 |
+
|
192 |
+
Provide your analysis and conclusions following the guidelines above."""
|
193 |
+
|
194 |
+
payload = {
|
195 |
+
"model": "Meta-Llama-3.1-8B-Instruct",
|
196 |
+
"messages": [
|
197 |
+
{"role": "system", "content": system_prompt},
|
198 |
+
{"role": "user", "content": user_prompt}
|
199 |
+
],
|
200 |
+
"max_tokens": 1000,
|
201 |
+
"temperature": 0.2,
|
202 |
+
"top_p": 0.9,
|
203 |
+
"stop": ["<|eot_id|>"]
|
204 |
}
|
205 |
+
|
206 |
+
try:
|
207 |
+
response = requests.post(url, headers=headers, json=payload)
|
208 |
+
if response.status_code == 200:
|
209 |
+
data = response.json()
|
210 |
+
ai_response = data['choices'][0]['message']['content']
|
211 |
+
# Parsowanie odpowiedzi
|
212 |
+
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
213 |
+
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
214 |
+
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
215 |
+
|
216 |
+
analysis_text = analysis.group(1).strip() if analysis else "No analysis available."
|
217 |
+
risk_text = risk_assessment.group(1).strip() if risk_assessment else "No risk assessment available."
|
218 |
+
recommendations_text = recommendations.group(1).strip() if recommendations else "No recommendations available."
|
219 |
+
|
220 |
+
return analysis_text, risk_text, recommendations_text
|
221 |
+
else:
|
222 |
+
logging.error(f"API Error: {response.status_code} - {response.text}")
|
223 |
+
return f"API Error: {response.status_code} - {response.text}", "Analysis Error.", "Analysis Error."
|
224 |
+
except Exception as e:
|
225 |
+
logging.error(f"API Connection Error: {e}")
|
226 |
+
return f"API Connection Error: {e}", "Analysis Error.", "Analysis Error."
|
227 |
+
|
228 |
+
# Inicjalizacja pliku statystyk
|
229 |
+
def init_stats_file():
|
230 |
+
stats_file = 'stats.json'
|
231 |
+
if not os.path.exists(stats_file):
|
232 |
+
with open(stats_file, 'w') as f:
|
233 |
+
json.dump({"total_analyses": 0, "total_frauds_detected": 0}, f)
|
234 |
+
|
235 |
+
# Pobranie statystyk
|
236 |
+
def get_stats():
|
237 |
+
stats_file = 'stats.json'
|
238 |
+
try:
|
239 |
+
with open(stats_file, 'r') as f:
|
240 |
+
stats = json.load(f)
|
241 |
+
return stats
|
242 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
243 |
+
return {"total_analyses": 0, "total_frauds_detected": 0}
|
244 |
+
|
245 |
+
# Aktualizacja statystyk analizy
|
246 |
+
def update_stats(fraud_detected=False):
|
247 |
+
stats_file = 'stats.json'
|
248 |
+
try:
|
249 |
+
with open(stats_file, 'r') as f:
|
250 |
+
stats = json.load(f)
|
251 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
252 |
+
stats = {"total_analyses": 0, "total_frauds_detected": 0}
|
253 |
+
|
254 |
+
stats["total_analyses"] += 1
|
255 |
+
if fraud_detected:
|
256 |
+
stats["total_frauds_detected"] += 1
|
257 |
+
|
258 |
+
with open(stats_file, 'w') as f:
|
259 |
+
json.dump(stats, f, indent=4)
|
260 |
+
|
261 |
+
# Inicjalizacja pliku historii analiz
|
262 |
+
def init_history_file():
|
263 |
+
history_file = 'history.json'
|
264 |
+
if not os.path.exists(history_file):
|
265 |
+
with open(history_file, 'w') as f:
|
266 |
+
json.dump([], f)
|
267 |
+
|
268 |
+
# Dodanie wpisu do historii analiz
|
269 |
+
def add_to_history(message, phone_number, analysis, risk, recommendations):
|
270 |
+
history_file = 'history.json'
|
271 |
+
try:
|
272 |
+
with open(history_file, 'r') as f:
|
273 |
+
history = json.load(f)
|
274 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
275 |
+
history = []
|
276 |
+
|
277 |
+
history.append({
|
278 |
+
"timestamp": datetime.now().isoformat(),
|
279 |
+
"message": message,
|
280 |
+
"phone_number": phone_number,
|
281 |
+
"analysis": analysis,
|
282 |
+
"risk_assessment": risk,
|
283 |
+
"recommendations": recommendations
|
284 |
+
})
|
285 |
+
|
286 |
+
with open(history_file, 'w') as f:
|
287 |
+
json.dump(history, f, indent=4)
|
288 |
+
|
289 |
+
# Pobranie historii analiz
|
290 |
+
def get_history():
|
291 |
+
history_file = 'history.json'
|
292 |
+
try:
|
293 |
+
with open(history_file, 'r') as f:
|
294 |
+
history = json.load(f)
|
295 |
+
return history
|
296 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
297 |
+
return []
|
298 |
+
|