File size: 5,001 Bytes
d3bd683
7703295
 
 
5c2815c
7703295
ffb7797
7703295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3bd683
 
 
df571be
7703295
 
d3bd683
 
 
7703295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb7797
7703295
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
import os
import requests
import pandas as pd
import streamlit as st
import plotly.express as px
import numpy as np
from datetime import datetime
from transformers import pipeline
from dotenv import load_dotenv

# ========================
# CONFIG
# ========================
load_dotenv()
SERPAPI_KEY = os.getenv("SERPAPI_KEY")

st.set_page_config(layout="wide")
st.title("🔥 OSINT BRI Monitoring System (PRO)")

# ========================
# MODELS
# ========================
@st.cache_resource
def load_models():
    sentiment = pipeline(
        "sentiment-analysis",
        model="cardiffnlp/twitter-roberta-base-sentiment"
    )

    risk = pipeline(
        "zero-shot-classification",
        model="facebook/bart-large-mnli"
    )

    return sentiment, risk

sentiment_model, risk_model = load_models()

# ========================
# DATA COLLECTOR
# ========================
def get_news(query):
    url = "https://serpapi.com/search.json"

    params = {
        "q": query,
        "hl": "ru",
        "gl": "kz",
        "api_key": SERPAPI_KEY
    }

    try:
        res = requests.get(url, params=params)
        data = res.json()

        rows = []
        for item in data.get("organic_results", []):
            rows.append({
                "text": item.get("title", "") + " " + item.get("snippet", ""),
                "time": datetime.now()
            })

        return rows

    except:
        return []

def get_social():
    # можно заменить на API
    return [
        {"text": "AI риски растут", "time": datetime.now()},
        {"text": "Проблемы безопасности LLM", "time": datetime.now()},
        {"text": "Рост технологий в Казахстане", "time": datetime.now()}
    ]

# ========================
# RISK LABELS
# ========================
RISK_LABELS = [
    "bias",
    "hallucination",
    "security",
    "misuse",
    "regulation"
]

# ========================
# NLP ENGINE
# ========================
def analyze(data):
    results = []

    for row in data:
        t = row["text"]

        try:
            sent = sentiment_model(t)[0]
            risk = risk_model(t, RISK_LABELS)

            results.append({
                "text": t,
                "time": row["time"],
                "sentiment": sent["label"],
                "sent_score": sent["score"],
                "risk": risk["labels"][0],
                "risk_score": risk["scores"][0]
            })
        except:
            continue

    return pd.DataFrame(results)

# ========================
# ADVANCED BRI
# ========================
def compute_bri(df):

    if df.empty:
        return 100

    neg = (df["sentiment"] == "NEGATIVE").mean()
    risk = df["risk_score"].mean()

    # аномалия (всплеск)
    volume = len(df)
    anomaly = np.std(df["risk_score"]) if len(df) > 1 else 0

    # веса
    w = {
        "risk": 0.4,
        "sent": 0.3,
        "volume": 0.2,
        "anomaly": 0.1
    }

    score = 100 - (
        w["risk"] * risk * 100 +
        w["sent"] * neg * 100 +
        w["volume"] * min(volume, 50) +
        w["anomaly"] * anomaly * 100
    )

    return max(0, min(100, score))

# ========================
# UI
# ========================
query = st.text_input("🔍 Бренд / тема", "LLM Kazakhstan")

if st.button("🚀 Запустить мониторинг"):

    with st.spinner("Сбор и анализ данных..."):

        data = get_news(query) + get_social()
        df = analyze(data)

        bri = compute_bri(df)

    # ========================
    # KPI
    # ========================
    col1, col2, col3 = st.columns(3)

    col1.metric("📊 BRI Index", round(bri, 2))
    col2.metric("⚠️ Avg Risk", round(df["risk_score"].mean(), 2))
    col3.metric("💬 Mentions", len(df))

    # ========================
    # TIME SERIES
    # ========================
    st.subheader("📈 Динамика")

    df["time"] = pd.to_datetime(df["time"])

    ts = df.groupby(df["time"].dt.hour).size().reset_index(name="count")

    st.plotly_chart(px.line(ts, x="time", y="count"))

    # ========================
    # SENTIMENT
    # ========================
    st.subheader("🥧 Sentiment")
    st.plotly_chart(px.pie(df, names="sentiment"))

    # ========================
    # RISK
    # ========================
    st.subheader("⚠️ Risk Distribution")
    st.plotly_chart(px.bar(df["risk"].value_counts()))

    # ========================
    # HEATMAP
    # ========================
    st.subheader("🔥 Risk vs Sentiment")

    pivot = pd.crosstab(df["risk"], df["sentiment"])

    st.plotly_chart(px.imshow(pivot, text_auto=True))

    # ========================
    # ALERT SYSTEM
    # ========================
    if bri < 60:
        st.error("🚨 Reputation Risk Detected!")

    elif bri < 80:
        st.warning("⚠️ Moderate Risk")

    else:
        st.success("✅ Stable Reputation")

    st.dataframe(df)