Spaces:
Running
Running
Update utils/functions.py
Browse files- utils/functions.py +69 -37
utils/functions.py
CHANGED
@@ -1,3 +1,5 @@
|
|
|
|
|
|
1 |
import phonenumbers
|
2 |
from phonenumbers import geocoder, carrier
|
3 |
import re
|
@@ -8,55 +10,68 @@ from datetime import datetime
|
|
8 |
import logging
|
9 |
|
10 |
# Konfiguracja logowania
|
11 |
-
logging.basicConfig(filename='app.log', level=logging.
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
59 |
except (json.JSONDecodeError, FileNotFoundError):
|
|
|
60 |
return False
|
61 |
|
62 |
# Funkcja do weryfikacji numeru telefonu
|
@@ -65,8 +80,10 @@ def get_phone_info(phone_number):
|
|
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
|
@@ -94,7 +111,7 @@ 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}"
|
@@ -180,7 +197,7 @@ Your response should be formatted exactly as specified above, using the <analysi
|
|
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}"
|
@@ -227,52 +244,62 @@ Provide your analysis and conclusions following the guidelines above."""
|
|
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 |
-
|
259 |
-
|
|
|
|
|
|
|
|
|
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(),
|
@@ -283,16 +310,21 @@ def add_to_history(message, phone_number, analysis, risk, recommendations):
|
|
283 |
"recommendations": recommendations
|
284 |
})
|
285 |
|
286 |
-
|
287 |
-
|
|
|
|
|
|
|
|
|
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 |
-
|
|
|
1 |
+
# utils/functions.py
|
2 |
+
|
3 |
import phonenumbers
|
4 |
from phonenumbers import geocoder, carrier
|
5 |
import re
|
|
|
10 |
import logging
|
11 |
|
12 |
# Konfiguracja logowania
|
13 |
+
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')
|
14 |
+
|
15 |
+
# Inicjalizacja 艣cie偶ki bazowej
|
16 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
17 |
|
18 |
# 艢cie偶ka do pliku JSON przechowuj膮cego fa艂szywe numery
|
19 |
+
FAKE_NUMBERS_FILE = os.path.join(BASE_DIR, '..', 'fake_numbers.json')
|
20 |
|
21 |
# Inicjalizacja pliku JSON przechowuj膮cego fa艂szywe numery
|
22 |
def init_fake_numbers_file():
|
23 |
if not os.path.exists(FAKE_NUMBERS_FILE):
|
24 |
+
with open(FAKE_NUMBERS_FILE, 'w', encoding='utf-8') as f:
|
25 |
+
json.dump([], f, ensure_ascii=False, indent=4)
|
26 |
+
logging.info(f"Utworzono nowy plik {FAKE_NUMBERS_FILE}.")
|
27 |
else:
|
28 |
try:
|
29 |
+
with open(FAKE_NUMBERS_FILE, 'r', encoding='utf-8') as f:
|
30 |
json.load(f)
|
31 |
+
logging.info(f"Plik {FAKE_NUMBERS_FILE} zosta艂 za艂adowany pomy艣lnie.")
|
32 |
except json.JSONDecodeError:
|
33 |
# Je艣li plik jest uszkodzony lub pusty, zresetuj go do pustej listy
|
34 |
+
with open(FAKE_NUMBERS_FILE, 'w', encoding='utf-8') as f:
|
35 |
+
json.dump([], f, ensure_ascii=False, indent=4)
|
36 |
+
logging.warning(f"Plik {FAKE_NUMBERS_FILE} by艂 uszkodzony i zosta艂 zresetowany.")
|
37 |
|
38 |
# Dodanie numeru telefonu do pliku JSON
|
39 |
def add_fake_number(phone_number):
|
40 |
+
logging.info(f"Pr贸buj臋 doda膰 numer: {phone_number}")
|
41 |
try:
|
42 |
+
with open(FAKE_NUMBERS_FILE, 'r', encoding='utf-8') as f:
|
43 |
fake_numbers = json.load(f)
|
44 |
except (json.JSONDecodeError, FileNotFoundError):
|
45 |
fake_numbers = []
|
46 |
+
logging.warning(f"{FAKE_NUMBERS_FILE} jest pusty lub uszkodzony. Inicjalizuj臋 now膮 list臋.")
|
47 |
+
|
48 |
if not any(entry["phone_number"] == phone_number for entry in fake_numbers):
|
49 |
fake_numbers.append({
|
50 |
"phone_number": phone_number,
|
51 |
"reported_at": datetime.now().isoformat()
|
52 |
})
|
53 |
try:
|
54 |
+
with open(FAKE_NUMBERS_FILE, 'w', encoding='utf-8') as f:
|
55 |
+
json.dump(fake_numbers, f, ensure_ascii=False, indent=4)
|
56 |
+
logging.info(f"Numer {phone_number} zosta艂 pomy艣lnie dodany do fake_numbers.json.")
|
57 |
return True
|
58 |
except Exception as e:
|
59 |
logging.error(f"Nie uda艂o si臋 zapisa膰 numeru {phone_number}: {e}")
|
60 |
return False
|
61 |
else:
|
62 |
+
logging.info(f"Numer {phone_number} ju偶 istnieje w fake_numbers.json.")
|
63 |
return False # Numer ju偶 istnieje
|
64 |
|
65 |
# Sprawdzenie, czy numer telefonu jest w pliku JSON
|
66 |
def is_fake_number(phone_number):
|
67 |
try:
|
68 |
+
with open(FAKE_NUMBERS_FILE, 'r', encoding='utf-8') as f:
|
69 |
fake_numbers = json.load(f)
|
70 |
+
exists = any(entry["phone_number"] == phone_number for entry in fake_numbers)
|
71 |
+
logging.info(f"Sprawdzanie numeru {phone_number}: {'znaleziony' if exists else 'nie znaleziony'}.")
|
72 |
+
return exists
|
73 |
except (json.JSONDecodeError, FileNotFoundError):
|
74 |
+
logging.error(f"Nie uda艂o si臋 za艂adowa膰 {FAKE_NUMBERS_FILE}.")
|
75 |
return False
|
76 |
|
77 |
# Funkcja do weryfikacji numeru telefonu
|
|
|
80 |
parsed_number = phonenumbers.parse(phone_number, None)
|
81 |
country = geocoder.description_for_number(parsed_number, 'pl')
|
82 |
operator = carrier.name_for_number(parsed_number, 'pl')
|
83 |
+
logging.info(f"Numer {phone_number} - Kraj: {country}, Operator: {operator}.")
|
84 |
return country, operator
|
85 |
+
except phonenumbers.NumberParseException as e:
|
86 |
+
logging.error(f"Nie uda艂o si臋 przetworzy膰 numeru telefonu {phone_number}: {e}")
|
87 |
return None, None
|
88 |
|
89 |
# Proste sprawdzenia heurystyczne wiadomo艣ci
|
|
|
111 |
if not api_key:
|
112 |
logging.error("Brak klucza API.")
|
113 |
return "Brak klucza API.", "Brak klucza API.", "Brak klucza API."
|
114 |
+
|
115 |
url = "https://api.sambanova.ai/v1/chat/completions"
|
116 |
headers = {
|
117 |
"Authorization": f"Bearer {api_key}"
|
|
|
197 |
}
|
198 |
|
199 |
system_prompt = system_prompts.get(language, system_prompts['English']) # Default to English if language not found
|
200 |
+
|
201 |
user_prompt = f"""Analyze the following message for potential fraud:
|
202 |
|
203 |
Message: "{message}"
|
|
|
244 |
|
245 |
# Inicjalizacja pliku statystyk
|
246 |
def init_stats_file():
|
247 |
+
stats_file = os.path.join(BASE_DIR, '..', 'stats.json')
|
248 |
if not os.path.exists(stats_file):
|
249 |
+
with open(stats_file, 'w', encoding='utf-8') as f:
|
250 |
+
json.dump({"total_analyses": 0, "total_frauds_detected": 0}, f, ensure_ascii=False, indent=4)
|
251 |
+
logging.info(f"Utworzono nowy plik statystyk {stats_file}.")
|
252 |
|
253 |
# Pobranie statystyk
|
254 |
def get_stats():
|
255 |
+
stats_file = os.path.join(BASE_DIR, '..', 'stats.json')
|
256 |
try:
|
257 |
+
with open(stats_file, 'r', encoding='utf-8') as f:
|
258 |
stats = json.load(f)
|
259 |
+
logging.info("Statystyki zosta艂y pobrane pomy艣lnie.")
|
260 |
return stats
|
261 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
262 |
+
logging.error(f"Nie uda艂o si臋 za艂adowa膰 statystyk: {e}")
|
263 |
return {"total_analyses": 0, "total_frauds_detected": 0}
|
264 |
|
265 |
# Aktualizacja statystyk analizy
|
266 |
def update_stats(fraud_detected=False):
|
267 |
+
stats_file = os.path.join(BASE_DIR, '..', 'stats.json')
|
268 |
try:
|
269 |
+
with open(stats_file, 'r', encoding='utf-8') as f:
|
270 |
stats = json.load(f)
|
271 |
except (json.JSONDecodeError, FileNotFoundError):
|
272 |
stats = {"total_analyses": 0, "total_frauds_detected": 0}
|
273 |
+
logging.warning(f"{stats_file} jest pusty lub uszkodzony. Inicjalizuj臋 now膮 list臋.")
|
274 |
|
275 |
stats["total_analyses"] += 1
|
276 |
if fraud_detected:
|
277 |
stats["total_frauds_detected"] += 1
|
278 |
|
279 |
+
try:
|
280 |
+
with open(stats_file, 'w', encoding='utf-8') as f:
|
281 |
+
json.dump(stats, f, ensure_ascii=False, indent=4)
|
282 |
+
logging.info(f"Statystyki zosta艂y zaktualizowane: {stats}.")
|
283 |
+
except Exception as e:
|
284 |
+
logging.error(f"Nie uda艂o si臋 zaktualizowa膰 statystyk: {e}")
|
285 |
|
286 |
# Inicjalizacja pliku historii analiz
|
287 |
def init_history_file():
|
288 |
+
history_file = os.path.join(BASE_DIR, '..', 'history.json')
|
289 |
if not os.path.exists(history_file):
|
290 |
+
with open(history_file, 'w', encoding='utf-8') as f:
|
291 |
+
json.dump([], f, ensure_ascii=False, indent=4)
|
292 |
+
logging.info(f"Utworzono nowy plik historii analiz {history_file}.")
|
293 |
|
294 |
# Dodanie wpisu do historii analiz
|
295 |
def add_to_history(message, phone_number, analysis, risk, recommendations):
|
296 |
+
history_file = os.path.join(BASE_DIR, '..', 'history.json')
|
297 |
try:
|
298 |
+
with open(history_file, 'r', encoding='utf-8') as f:
|
299 |
history = json.load(f)
|
300 |
except (json.JSONDecodeError, FileNotFoundError):
|
301 |
history = []
|
302 |
+
logging.warning(f"{history_file} jest pusty lub uszkodzony. Inicjalizuj臋 now膮 list臋.")
|
303 |
|
304 |
history.append({
|
305 |
"timestamp": datetime.now().isoformat(),
|
|
|
310 |
"recommendations": recommendations
|
311 |
})
|
312 |
|
313 |
+
try:
|
314 |
+
with open(history_file, 'w', encoding='utf-8') as f:
|
315 |
+
json.dump(history, f, ensure_ascii=False, indent=4)
|
316 |
+
logging.info(f"Dodano wpis do historii analiz dla numeru {phone_number}.")
|
317 |
+
except Exception as e:
|
318 |
+
logging.error(f"Nie uda艂o si臋 zapisa膰 historii analiz dla numeru {phone_number}: {e}")
|
319 |
|
320 |
# Pobranie historii analiz
|
321 |
def get_history():
|
322 |
+
history_file = os.path.join(BASE_DIR, '..', 'history.json')
|
323 |
try:
|
324 |
+
with open(history_file, 'r', encoding='utf-8') as f:
|
325 |
history = json.load(f)
|
326 |
+
logging.info("Historia analiz zosta艂a pobrana pomy艣lnie.")
|
327 |
return history
|
328 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
329 |
+
logging.error(f"Nie uda艂o si臋 za艂adowa膰 historii analiz: {e}")
|
330 |
return []
|
|