Spaces:
Running
Running
Update utils/functions.py
Browse files- utils/functions.py +83 -157
utils/functions.py
CHANGED
@@ -1,3 +1,5 @@
|
|
|
|
|
|
1 |
import phonenumbers
|
2 |
from phonenumbers import geocoder, carrier, NumberParseException
|
3 |
import re
|
@@ -6,30 +8,30 @@ import os
|
|
6 |
from datetime import datetime
|
7 |
import logging
|
8 |
import json
|
9 |
-
import whois #
|
10 |
from PIL import Image
|
11 |
-
import pytesseract #
|
12 |
|
13 |
-
#
|
14 |
logging.basicConfig(
|
15 |
filename='app.log',
|
16 |
level=logging.INFO,
|
17 |
format='%(asctime)s %(levelname)s:%(message)s'
|
18 |
)
|
19 |
|
20 |
-
#
|
21 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
22 |
DATA_DIR = os.path.join(BASE_DIR, '..', 'data')
|
23 |
FAKE_NUMBERS_FILE = os.path.join(DATA_DIR, 'fake_numbers.json')
|
24 |
HISTORY_FILE = os.path.join(DATA_DIR, 'history.json')
|
25 |
STATS_FILE = os.path.join(DATA_DIR, 'stats.json')
|
26 |
|
27 |
-
#
|
28 |
os.makedirs(DATA_DIR, exist_ok=True)
|
29 |
|
30 |
-
#
|
31 |
def load_json(file_path):
|
32 |
-
"""
|
33 |
if not os.path.exists(file_path):
|
34 |
if file_path.endswith('stats.json'):
|
35 |
return {"total_analyses": 0, "total_frauds_detected": 0}
|
@@ -40,46 +42,47 @@ def load_json(file_path):
|
|
40 |
data = json.load(file)
|
41 |
return data
|
42 |
except json.JSONDecodeError:
|
43 |
-
logging.error(f"
|
44 |
if file_path.endswith('stats.json'):
|
45 |
return {"total_analyses": 0, "total_frauds_detected": 0}
|
46 |
return []
|
47 |
|
48 |
def save_json(file_path, data):
|
49 |
-
"""
|
50 |
with open(file_path, 'w', encoding='utf-8') as file:
|
51 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
52 |
-
logging.info(f"
|
53 |
|
54 |
-
#
|
55 |
def add_fake_number(phone_number):
|
56 |
-
"""
|
57 |
fake_numbers = load_json(FAKE_NUMBERS_FILE)
|
58 |
if phone_number not in fake_numbers:
|
59 |
fake_numbers.append(phone_number)
|
60 |
save_json(FAKE_NUMBERS_FILE, fake_numbers)
|
61 |
-
logging.info(f"
|
62 |
return True
|
63 |
else:
|
64 |
-
logging.info(f"
|
65 |
return False
|
66 |
|
67 |
def is_fake_number(phone_number):
|
68 |
-
"""
|
69 |
fake_numbers = load_json(FAKE_NUMBERS_FILE)
|
70 |
exists = phone_number in fake_numbers
|
71 |
-
logging.info(f"
|
72 |
return exists
|
73 |
|
74 |
def get_fake_numbers():
|
75 |
-
"""
|
76 |
fake_numbers = load_json(FAKE_NUMBERS_FILE)
|
77 |
return fake_numbers
|
78 |
|
79 |
-
#
|
80 |
def simple_checks(message, language):
|
81 |
-
"""
|
82 |
warnings = []
|
|
|
83 |
scam_keywords = {
|
84 |
'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'],
|
85 |
'German': ['Geld', 'Überweisung', 'Passwort', 'Code', 'Preis', 'Gewinn', 'dringend', 'Hilfe', 'Gebühr', 'Bank', 'Karte', 'Konto', 'Anmeldung', 'Transaktion', 'Verifizierung', 'persönliche Daten', 'schnelle Zahlung', 'Kontosperrung', 'Benachrichtigung'],
|
@@ -87,24 +90,23 @@ def simple_checks(message, language):
|
|
87 |
}
|
88 |
|
89 |
selected_keywords = scam_keywords.get(language, scam_keywords['English'])
|
90 |
-
|
91 |
message_lower = message.lower()
|
92 |
|
93 |
if any(keyword.lower() in message_lower for keyword in selected_keywords):
|
94 |
-
warnings.append("
|
95 |
if re.search(r'http[s]?://', message):
|
96 |
-
warnings.append("
|
97 |
if re.search(r'\b(podaj|prześlij|udostępnij|sende|übermittle|teile|send|provide|share)\b.*\b(hasło|kod|dane osobowe|numer konta|Passwort|Code|persönliche Daten|Kontonummer|password|code|personal information|account number)\b', message_lower):
|
98 |
-
warnings.append("
|
99 |
return warnings
|
100 |
|
101 |
def analyze_message(content, sender_info, additional_info, api_key, language):
|
102 |
-
"""
|
103 |
if not api_key:
|
104 |
-
logging.error("
|
105 |
-
return "
|
106 |
|
107 |
-
url = "https://api.sambanova.ai/v1/chat/completions"
|
108 |
headers = {
|
109 |
"Authorization": f"Bearer {api_key}",
|
110 |
"Content-Type": "application/json"
|
@@ -112,29 +114,29 @@ def analyze_message(content, sender_info, additional_info, api_key, language):
|
|
112 |
|
113 |
system_prompts = {
|
114 |
'Polish': """
|
115 |
-
|
116 |
|
117 |
<analysis>
|
118 |
-
**
|
119 |
-
-
|
120 |
-
-
|
121 |
-
-
|
122 |
</analysis>
|
123 |
|
124 |
<risk_assessment>
|
125 |
-
**
|
126 |
-
-
|
127 |
-
-
|
128 |
</risk_assessment>
|
129 |
|
130 |
<recommendations>
|
131 |
-
**
|
132 |
-
-
|
133 |
-
-
|
134 |
-
-
|
135 |
</recommendations>
|
136 |
|
137 |
-
|
138 |
""",
|
139 |
'German': """
|
140 |
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:
|
@@ -201,7 +203,7 @@ Additional Information:
|
|
201 |
Provide your analysis and conclusions following the guidelines above."""
|
202 |
|
203 |
payload = {
|
204 |
-
"model": "Meta-Llama-3.1-8B-Instruct",
|
205 |
"messages": [
|
206 |
{"role": "system", "content": system_prompt},
|
207 |
{"role": "user", "content": user_prompt}
|
@@ -217,7 +219,7 @@ Provide your analysis and conclusions following the guidelines above."""
|
|
217 |
if response.status_code == 200:
|
218 |
data = response.json()
|
219 |
ai_response = data['choices'][0]['message']['content']
|
220 |
-
#
|
221 |
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
222 |
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
223 |
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
@@ -234,14 +236,14 @@ Provide your analysis and conclusions following the guidelines above."""
|
|
234 |
logging.error(f"Błąd połączenia z API: {e}")
|
235 |
return f"Błąd połączenia z API: {e}", "Błąd analizy.", "Błąd analizy."
|
236 |
|
237 |
-
#
|
238 |
def analyze_email_message(content, sender_info, additional_info, api_key, language):
|
239 |
-
"""
|
240 |
if not api_key:
|
241 |
-
logging.error("
|
242 |
-
return "
|
243 |
|
244 |
-
url = "https://api.sambanova.ai/v1/chat/completions"
|
245 |
headers = {
|
246 |
"Authorization": f"Bearer {api_key}",
|
247 |
"Content-Type": "application/json"
|
@@ -341,7 +343,7 @@ Additional Information:
|
|
341 |
Provide your analysis and conclusions following the guidelines above."""
|
342 |
|
343 |
payload = {
|
344 |
-
"model": "Meta-Llama-3.1-8B-Instruct",
|
345 |
"messages": [
|
346 |
{"role": "system", "content": system_prompt},
|
347 |
{"role": "user", "content": user_prompt}
|
@@ -357,7 +359,7 @@ Provide your analysis and conclusions following the guidelines above."""
|
|
357 |
if response.status_code == 200:
|
358 |
data = response.json()
|
359 |
ai_response = data['choices'][0]['message']['content']
|
360 |
-
#
|
361 |
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
362 |
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
363 |
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
@@ -374,118 +376,42 @@ Provide your analysis and conclusions following the guidelines above."""
|
|
374 |
logging.error(f"Błąd połączenia z API: {e}")
|
375 |
return f"Błąd połączenia z API: {e}", "Błąd analizy.", "Błąd analizy."
|
376 |
|
377 |
-
#
|
378 |
def analyze_website(url, api_key, language):
|
379 |
-
"""
|
380 |
if not api_key:
|
381 |
-
logging.error("
|
382 |
-
return "
|
383 |
-
|
384 |
-
phishing_urls = check_urls_with_phishtank([url])
|
385 |
-
unsafe_urls = check_urls_with_safe_browsing([url])
|
386 |
-
|
387 |
-
# Prepare the analysis results
|
388 |
-
if phishing_urls:
|
389 |
-
analysis_result = "The following URLs are flagged as phishing:"
|
390 |
-
for phishing_url in phishing_urls:
|
391 |
-
analysis_result += f"\n- {phishing_url}"
|
392 |
-
else:
|
393 |
-
analysis_result = "No phishing threats found."
|
394 |
|
395 |
-
if unsafe_urls:
|
396 |
-
analysis_result += "\nThe following URLs are flagged as unsafe:"
|
397 |
-
for unsafe_url in unsafe_urls:
|
398 |
-
analysis_result += f"\n- {unsafe_url}"
|
399 |
-
else:
|
400 |
-
analysis_result += "\nNo unsafe threats found."
|
401 |
-
|
402 |
-
return analysis_result
|
403 |
-
|
404 |
-
def check_urls_with_phishtank(urls):
|
405 |
-
"""Checks URLs with PhishTank for phishing threats."""
|
406 |
-
phishing_urls = []
|
407 |
-
for url in urls:
|
408 |
-
params = {
|
409 |
-
'format': 'json',
|
410 |
-
'url': url
|
411 |
-
}
|
412 |
-
try:
|
413 |
-
response = requests.post('https://checkurl.phishtank.com/checkurl/', data=params)
|
414 |
-
if response.status_code == 200:
|
415 |
-
data = response.json()
|
416 |
-
in_database = data.get('results', {}).get('in_database', False)
|
417 |
-
valid = data.get('results', {}).get('valid', False)
|
418 |
-
if in_database and valid:
|
419 |
-
phishing_urls.append(url)
|
420 |
-
else:
|
421 |
-
logging.warning(f"Error checking URL in PhishTank: {response.status_code}")
|
422 |
-
except Exception as e:
|
423 |
-
logging.error(f"Error checking URL in PhishTank: {e}")
|
424 |
-
return phishing_urls
|
425 |
-
|
426 |
-
def check_urls_with_safe_browsing(urls):
|
427 |
-
"""Checks URLs with Google Safe Browsing for unsafe threats."""
|
428 |
-
api_key = os.getenv('GOOGLE_SAFE_BROWSING_API_KEY')
|
429 |
-
if not api_key:
|
430 |
-
return None
|
431 |
-
unsafe_urls = []
|
432 |
-
headers = {'Content-Type': 'application/json'}
|
433 |
-
client_body = {
|
434 |
-
'client': {
|
435 |
-
'clientId': 'yourcompanyname',
|
436 |
-
'clientVersion': '1.0'
|
437 |
-
},
|
438 |
-
'threatInfo': {
|
439 |
-
'threatTypes': ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
|
440 |
-
'platformTypes': ["ANY_PLATFORM"],
|
441 |
-
'threatEntryTypes': ["URL"],
|
442 |
-
'threatEntries': [{'url': url} for url in urls]
|
443 |
-
}
|
444 |
-
}
|
445 |
try:
|
446 |
-
response = requests.
|
447 |
-
f'https://safebrowsing.googleapis.com/v4/threatMatches:find?key={api_key}',
|
448 |
-
headers=headers,
|
449 |
-
json=client_body
|
450 |
-
)
|
451 |
if response.status_code == 200:
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
else:
|
456 |
-
logging.error(f"
|
|
|
457 |
except Exception as e:
|
458 |
-
logging.error(f"
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
"
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
if fraud_detected:
|
481 |
-
stats["total_frauds_detected"] += 1
|
482 |
-
save_json(STATS_FILE, stats)
|
483 |
-
logging.info(f"Statistics updated: Analyses {stats['total_analyses']}, Frauds {stats['total_frauds_detected']}.")
|
484 |
-
|
485 |
-
def get_stats():
|
486 |
-
"""Retrieves analysis statistics from stats.json."""
|
487 |
-
stats = load_json(STATS_FILE)
|
488 |
-
logging.info("Statistics retrieved successfully.")
|
489 |
-
return stats
|
490 |
-
|
491 |
-
# Additional functions can be added as required
|
|
|
1 |
+
# utils/functions.py
|
2 |
+
|
3 |
import phonenumbers
|
4 |
from phonenumbers import geocoder, carrier, NumberParseException
|
5 |
import re
|
|
|
8 |
from datetime import datetime
|
9 |
import logging
|
10 |
import json
|
11 |
+
import whois # Upewnij się, że moduł 'python-whois' jest zainstalowany: pip install python-whois
|
12 |
from PIL import Image
|
13 |
+
import pytesseract # Upewnij się, że moduł 'pytesseract' jest zainstalowany: pip install pytesseract
|
14 |
|
15 |
+
# Konfiguracja logowania
|
16 |
logging.basicConfig(
|
17 |
filename='app.log',
|
18 |
level=logging.INFO,
|
19 |
format='%(asctime)s %(levelname)s:%(message)s'
|
20 |
)
|
21 |
|
22 |
+
# Definiowanie ścieżek do plików JSON
|
23 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
24 |
DATA_DIR = os.path.join(BASE_DIR, '..', 'data')
|
25 |
FAKE_NUMBERS_FILE = os.path.join(DATA_DIR, 'fake_numbers.json')
|
26 |
HISTORY_FILE = os.path.join(DATA_DIR, 'history.json')
|
27 |
STATS_FILE = os.path.join(DATA_DIR, 'stats.json')
|
28 |
|
29 |
+
# Upewnij się, że katalog 'data' istnieje
|
30 |
os.makedirs(DATA_DIR, exist_ok=True)
|
31 |
|
32 |
+
# Funkcje pomocnicze
|
33 |
def load_json(file_path):
|
34 |
+
"""Ładuje dane z pliku JSON. Jeśli plik nie istnieje, zwraca pustą listę lub domyślny obiekt."""
|
35 |
if not os.path.exists(file_path):
|
36 |
if file_path.endswith('stats.json'):
|
37 |
return {"total_analyses": 0, "total_frauds_detected": 0}
|
|
|
42 |
data = json.load(file)
|
43 |
return data
|
44 |
except json.JSONDecodeError:
|
45 |
+
logging.error(f"Nie można załadować danych z {file_path}. Plik jest uszkodzony.")
|
46 |
if file_path.endswith('stats.json'):
|
47 |
return {"total_analyses": 0, "total_frauds_detected": 0}
|
48 |
return []
|
49 |
|
50 |
def save_json(file_path, data):
|
51 |
+
"""Zapisuje dane do pliku JSON."""
|
52 |
with open(file_path, 'w', encoding='utf-8') as file:
|
53 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
54 |
+
logging.info(f"Dane zostały zapisane do {file_path}.")
|
55 |
|
56 |
+
# Funkcje związane z fałszywymi numerami telefonów
|
57 |
def add_fake_number(phone_number):
|
58 |
+
"""Dodaje numer telefonu do pliku fake_numbers.json jako fałszywy, jeśli jeszcze go tam nie ma."""
|
59 |
fake_numbers = load_json(FAKE_NUMBERS_FILE)
|
60 |
if phone_number not in fake_numbers:
|
61 |
fake_numbers.append(phone_number)
|
62 |
save_json(FAKE_NUMBERS_FILE, fake_numbers)
|
63 |
+
logging.info(f"Numer {phone_number} został pomyślnie dodany do fake_numbers.json.")
|
64 |
return True
|
65 |
else:
|
66 |
+
logging.info(f"Numer {phone_number} już istnieje w fake_numbers.json.")
|
67 |
return False
|
68 |
|
69 |
def is_fake_number(phone_number):
|
70 |
+
"""Sprawdza, czy dany numer telefonu jest oznaczony jako fałszywy w pliku fake_numbers.json."""
|
71 |
fake_numbers = load_json(FAKE_NUMBERS_FILE)
|
72 |
exists = phone_number in fake_numbers
|
73 |
+
logging.info(f"Sprawdzanie numeru {phone_number}: {'znaleziony' if exists else 'nie znaleziony'}.")
|
74 |
return exists
|
75 |
|
76 |
def get_fake_numbers():
|
77 |
+
"""Pobiera listę fałszywych numerów z pliku fake_numbers.json."""
|
78 |
fake_numbers = load_json(FAKE_NUMBERS_FILE)
|
79 |
return fake_numbers
|
80 |
|
81 |
+
# Funkcje analizy SMS
|
82 |
def simple_checks(message, language):
|
83 |
+
"""Przeprowadza proste sprawdzenia heurystyczne wiadomości SMS."""
|
84 |
warnings = []
|
85 |
+
# Baza słów kluczowych (polski, niemiecki, angielski)
|
86 |
scam_keywords = {
|
87 |
'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'],
|
88 |
'German': ['Geld', 'Überweisung', 'Passwort', 'Code', 'Preis', 'Gewinn', 'dringend', 'Hilfe', 'Gebühr', 'Bank', 'Karte', 'Konto', 'Anmeldung', 'Transaktion', 'Verifizierung', 'persönliche Daten', 'schnelle Zahlung', 'Kontosperrung', 'Benachrichtigung'],
|
|
|
90 |
}
|
91 |
|
92 |
selected_keywords = scam_keywords.get(language, scam_keywords['English'])
|
|
|
93 |
message_lower = message.lower()
|
94 |
|
95 |
if any(keyword.lower() in message_lower for keyword in selected_keywords):
|
96 |
+
warnings.append("Wiadomość zawiera słowa kluczowe związane z potencjalnym oszustwem.")
|
97 |
if re.search(r'http[s]?://', message):
|
98 |
+
warnings.append("Wiadomość zawiera link.")
|
99 |
if re.search(r'\b(podaj|prześlij|udostępnij|sende|übermittle|teile|send|provide|share)\b.*\b(hasło|kod|dane osobowe|numer konta|Passwort|Code|persönliche Daten|Kontonummer|password|code|personal information|account number)\b', message_lower):
|
100 |
+
warnings.append("Wiadomość zawiera prośbę o poufne informacje.")
|
101 |
return warnings
|
102 |
|
103 |
def analyze_message(content, sender_info, additional_info, api_key, language):
|
104 |
+
"""Analizuje treść wiadomości SMS za pomocą modelu AI, wykorzystując system prompts."""
|
105 |
if not api_key:
|
106 |
+
logging.error("Brak klucza API.")
|
107 |
+
return "Brak klucza API.", "Brak klucza API.", "Brak klucza API."
|
108 |
|
109 |
+
url = "https://api.sambanova.ai/v1/chat/completions"
|
110 |
headers = {
|
111 |
"Authorization": f"Bearer {api_key}",
|
112 |
"Content-Type": "application/json"
|
|
|
114 |
|
115 |
system_prompts = {
|
116 |
'Polish': """
|
117 |
+
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:
|
118 |
|
119 |
<analysis>
|
120 |
+
**Analiza Treści Wiadomości:**
|
121 |
+
- 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.
|
122 |
+
- Opisz kontekst językowy i kulturowy wiadomości.
|
123 |
+
- Zidentyfikuj wszelkie elementy, które mogą sugerować, że wiadomość jest próbą wyłudzenia informacji lub pieniędzy.
|
124 |
</analysis>
|
125 |
|
126 |
<risk_assessment>
|
127 |
+
**Ocena Ryzyka Oszustwa:**
|
128 |
+
- 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.
|
129 |
+
- Wyjaśnij, jakie czynniki wpływają na tę ocenę.
|
130 |
</risk_assessment>
|
131 |
|
132 |
<recommendations>
|
133 |
+
**Zalecenia dla Użytkownika:**
|
134 |
+
- Podaj jasne i konkretne zalecenia dotyczące dalszych kroków, które użytkownik powinien podjąć.
|
135 |
+
- Uwzględnij sugestie dotyczące bezpieczeństwa, takie jak blokowanie nadawcy, zgłaszanie wiadomości do odpowiednich instytucji, czy też ignorowanie wiadomości.
|
136 |
+
- 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.
|
137 |
</recommendations>
|
138 |
|
139 |
+
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.
|
140 |
""",
|
141 |
'German': """
|
142 |
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:
|
|
|
203 |
Provide your analysis and conclusions following the guidelines above."""
|
204 |
|
205 |
payload = {
|
206 |
+
"model": "Meta-Llama-3.1-8B-Instruct",
|
207 |
"messages": [
|
208 |
{"role": "system", "content": system_prompt},
|
209 |
{"role": "user", "content": user_prompt}
|
|
|
219 |
if response.status_code == 200:
|
220 |
data = response.json()
|
221 |
ai_response = data['choices'][0]['message']['content']
|
222 |
+
# Parsowanie odpowiedzi
|
223 |
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
224 |
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
225 |
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
|
|
236 |
logging.error(f"Błąd połączenia z API: {e}")
|
237 |
return f"Błąd połączenia z API: {e}", "Błąd analizy.", "Błąd analizy."
|
238 |
|
239 |
+
# Funkcje analizy email
|
240 |
def analyze_email_message(content, sender_info, additional_info, api_key, language):
|
241 |
+
"""Analizuje treść wiadomości email za pomocą modelu AI, wykorzystując system prompts."""
|
242 |
if not api_key:
|
243 |
+
logging.error("Brak klucza API.")
|
244 |
+
return "Brak klucza API.", "Brak klucza API.", "Brak klucza API."
|
245 |
|
246 |
+
url = "https://api.sambanova.ai/v1/chat/completions"
|
247 |
headers = {
|
248 |
"Authorization": f"Bearer {api_key}",
|
249 |
"Content-Type": "application/json"
|
|
|
343 |
Provide your analysis and conclusions following the guidelines above."""
|
344 |
|
345 |
payload = {
|
346 |
+
"model": "Meta-Llama-3.1-8B-Instruct",
|
347 |
"messages": [
|
348 |
{"role": "system", "content": system_prompt},
|
349 |
{"role": "user", "content": user_prompt}
|
|
|
359 |
if response.status_code == 200:
|
360 |
data = response.json()
|
361 |
ai_response = data['choices'][0]['message']['content']
|
362 |
+
# Parsowanie odpowiedzi
|
363 |
analysis = re.search(r'<analysis>(.*?)</analysis>', ai_response, re.DOTALL)
|
364 |
risk_assessment = re.search(r'<risk_assessment>(.*?)</risk_assessment>', ai_response, re.DOTALL)
|
365 |
recommendations = re.search(r'<recommendations>(.*?)</recommendations>', ai_response, re.DOTALL)
|
|
|
376 |
logging.error(f"Błąd połączenia z API: {e}")
|
377 |
return f"Błąd połączenia z API: {e}", "Błąd analizy.", "Błąd analizy."
|
378 |
|
379 |
+
# Funkcja analizy stron internetowych
|
380 |
def analyze_website(url, api_key, language):
|
381 |
+
"""Analizuje zawartość strony internetowej."""
|
382 |
if not api_key:
|
383 |
+
logging.error("Brak klucza API.")
|
384 |
+
return "Brak klucza API.", "Brak klucza API."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
386 |
try:
|
387 |
+
response = requests.get(url)
|
|
|
|
|
|
|
|
|
388 |
if response.status_code == 200:
|
389 |
+
content = response.text
|
390 |
+
logging.info(f"Zawartość strony {url} została pobrana pomyślnie.")
|
391 |
+
return content
|
392 |
else:
|
393 |
+
logging.error(f"Błąd podczas pobierania zawartości strony {url}: {response.status_code}")
|
394 |
+
return f"Błąd: {response.status_code}", "Błąd analizy strony.", "Błąd analizy strony."
|
395 |
except Exception as e:
|
396 |
+
logging.error(f"Błąd połączenia z {url}: {e}")
|
397 |
+
return f"Błąd połączenia z {url}: {e}", "Błąd analizy strony.", "Błąd analizy strony."
|
398 |
+
|
399 |
+
def get_phone_info(phone_number):
|
400 |
+
"""Weryfikuje numer telefonu i zwraca informacje o kraju i operatorze."""
|
401 |
+
try:
|
402 |
+
parsed_number = phonenumbers.parse(phone_number, None)
|
403 |
+
country = geocoder.description_for_number(parsed_number, 'pl')
|
404 |
+
operator = carrier.name_for_number(parsed_number, 'pl')
|
405 |
+
if not country:
|
406 |
+
country = "Nieznany"
|
407 |
+
if not operator:
|
408 |
+
operator = "Nieznany"
|
409 |
+
logging.info(f"Numer {phone_number} - Kraj: {country}, Operator: {operator}.")
|
410 |
+
return country, operator
|
411 |
+
except NumberParseException as e:
|
412 |
+
logging.error(f"Nie udało się przetworzyć numeru telefonu {phone_number}: {e}")
|
413 |
+
return "Nieznany", "Nieznany"
|
414 |
+
|
415 |
+
# Jeśli inne funkcje są używane, dodaj je tutaj
|
416 |
+
# ...
|
417 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|