Spaces:
Build error
Build error
Update database_manager.py
Browse files- database_manager.py +67 -27
database_manager.py
CHANGED
|
@@ -1,31 +1,32 @@
|
|
|
|
|
|
|
|
| 1 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 2 |
from huggingface_hub import HfApi, hf_hub_download
|
| 3 |
-
import
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
# إعداد
|
|
|
|
|
|
|
| 7 |
DATASET_ID = "MZ14E/epssar-database"
|
| 8 |
FILE_NAME = "security_logs.csv"
|
| 9 |
-
LOCAL_PATH = f"/tmp/{FILE_NAME}"
|
| 10 |
-
|
| 11 |
|
| 12 |
def save_to_database(tweet_text, analysis_result, risk_level):
|
| 13 |
-
"""حفظ نتائج
|
| 14 |
try:
|
| 15 |
-
# 1. محاولة تحميل الملف الحالي إذا كان موجوداً
|
| 16 |
try:
|
| 17 |
-
file_path = hf_hub_download(
|
| 18 |
-
repo_id=DATASET_ID,
|
| 19 |
-
filename=FILE_NAME,
|
| 20 |
-
repo_type="dataset",
|
| 21 |
-
token=TOKEN
|
| 22 |
-
)
|
| 23 |
df = pd.read_csv(file_path)
|
| 24 |
-
except
|
| 25 |
-
# إذا كان أول مرة أو الملف غير موجود، ننشئ جدول جديد
|
| 26 |
df = pd.DataFrame(columns=["date", "tweet", "analysis", "risk_level"])
|
| 27 |
|
| 28 |
-
# 2. إضافة البيانات الجديدة
|
| 29 |
new_entry = {
|
| 30 |
"date": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
| 31 |
"tweet": tweet_text,
|
|
@@ -33,19 +34,58 @@ def save_to_database(tweet_text, analysis_result, risk_level):
|
|
| 33 |
"risk_level": risk_level
|
| 34 |
}
|
| 35 |
df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)
|
| 36 |
-
|
| 37 |
-
# 3. حفظ الملف محلياً في المسار المؤقت ثم رفعه
|
| 38 |
df.to_csv(LOCAL_PATH, index=False)
|
| 39 |
|
| 40 |
api = HfApi()
|
| 41 |
-
api.upload_file(
|
| 42 |
-
path_or_fileobj=LOCAL_PATH,
|
| 43 |
-
path_in_repo=FILE_NAME,
|
| 44 |
-
repo_id=DATASET_ID,
|
| 45 |
-
repo_type="dataset",
|
| 46 |
-
token=TOKEN
|
| 47 |
-
)
|
| 48 |
return True
|
| 49 |
except Exception as e:
|
| 50 |
-
print(f"
|
| 51 |
-
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
import pandas as pd
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
from apify_client import ApifyClient
|
| 6 |
+
from google import genai
|
| 7 |
from huggingface_hub import HfApi, hf_hub_download
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
# تحميل الإعدادات
|
| 11 |
+
load_dotenv()
|
| 12 |
|
| 13 |
+
# إعداد العملاء والمفاتيح (Secrets)
|
| 14 |
+
client_apify = ApifyClient(os.getenv("APIFY_TOKEN"))
|
| 15 |
+
client_gemini = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
|
| 16 |
DATASET_ID = "MZ14E/epssar-database"
|
| 17 |
FILE_NAME = "security_logs.csv"
|
| 18 |
+
LOCAL_PATH = f"/tmp/{FILE_NAME}"
|
| 19 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 20 |
|
| 21 |
def save_to_database(tweet_text, analysis_result, risk_level):
|
| 22 |
+
"""دالة حفظ النتائج في الهقنق فيس"""
|
| 23 |
try:
|
|
|
|
| 24 |
try:
|
| 25 |
+
file_path = hf_hub_download(repo_id=DATASET_ID, filename=FILE_NAME, repo_type="dataset", token=HF_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
df = pd.read_csv(file_path)
|
| 27 |
+
except:
|
|
|
|
| 28 |
df = pd.DataFrame(columns=["date", "tweet", "analysis", "risk_level"])
|
| 29 |
|
|
|
|
| 30 |
new_entry = {
|
| 31 |
"date": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
| 32 |
"tweet": tweet_text,
|
|
|
|
| 34 |
"risk_level": risk_level
|
| 35 |
}
|
| 36 |
df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)
|
|
|
|
|
|
|
| 37 |
df.to_csv(LOCAL_PATH, index=False)
|
| 38 |
|
| 39 |
api = HfApi()
|
| 40 |
+
api.upload_file(path_or_fileobj=LOCAL_PATH, path_in_repo=FILE_NAME, repo_id=DATASET_ID, repo_type="dataset", token=HF_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
return True
|
| 42 |
except Exception as e:
|
| 43 |
+
print(f"Database Error: {e}")
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
def start_scanning(period_days):
|
| 47 |
+
today = datetime.now().strftime('%Y-%m-%d')
|
| 48 |
+
start_date = (datetime.now() - timedelta(days=int(period_days))).strftime('%Y-%m-%d')
|
| 49 |
+
|
| 50 |
+
yield "🔎 جاري سحب البيانات من تويتر وتحليلها..."
|
| 51 |
+
|
| 52 |
+
run_input = {
|
| 53 |
+
"searchTerms": ["خيانة الوطن", "إشاعة مغرضة", "المساس بالسيادة"],
|
| 54 |
+
"start": start_date, "end": today, "maxItems": 5, "place": "Saudi Arabia"
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
run = client_apify.actor("apidojo/tweet-scraper").call(run_input=run_input)
|
| 59 |
+
tweets = [item.get("full_text") for item in client_apify.dataset(run["defaultDatasetId"]).iterate_items()]
|
| 60 |
+
|
| 61 |
+
if not tweets:
|
| 62 |
+
yield "❌ لم يتم العثور على محتوى مشبوه."
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
all_tweets_text = "\n---\n".join(tweets)
|
| 66 |
+
prompt = f"أنت محلل أمني سعودي. حلل هذه التغريدات واستخرج التهديدات: {all_tweets_text}"
|
| 67 |
+
|
| 68 |
+
response = client_gemini.models.generate_content(model="gemini-2.0-flash", contents=prompt)
|
| 69 |
+
analysis = response.text
|
| 70 |
+
|
| 71 |
+
# حفظ التقرير في قاعدة البيانات تلقائياً
|
| 72 |
+
save_to_database(all_tweets_text[:500], analysis, "Medium/High")
|
| 73 |
+
|
| 74 |
+
yield f"✅ تم التحليل والحفظ بنجاح:\n\n{analysis}"
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
yield f"⚠️ خطأ: {str(e)}"
|
| 78 |
+
|
| 79 |
+
# واجهة Gradio
|
| 80 |
+
with gr.Blocks(title="إبصار - الرصد الأمني") as demo:
|
| 81 |
+
gr.Markdown("# 🛡️ نظام إبصار (EPSSAR)")
|
| 82 |
+
with gr.Row():
|
| 83 |
+
btn_1 = gr.Button("آخر 24 ساعة")
|
| 84 |
+
btn_3 = gr.Button("آخر 3 أيام")
|
| 85 |
+
output = gr.Markdown()
|
| 86 |
+
|
| 87 |
+
btn_1.click(fn=start_scanning, inputs=[gr.State(1)], outputs=output)
|
| 88 |
+
btn_3.click(fn=start_scanning, inputs=[gr.State(3)], outputs=output)
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
demo.launch()
|