QAway-to commited on
Commit
90ba9ea
·
1 Parent(s): 7043d8e

Base app.py interface v1.0

Browse files
Files changed (1) hide show
  1. app.py +56 -56
app.py CHANGED
@@ -1,14 +1,15 @@
1
- import requests, pandas as pd
2
- from transformers import pipeline
3
- from datetime import datetime, timedelta
4
  import gradio as gr
 
 
 
 
 
 
5
 
6
- # ============================================================
7
- # 1️⃣ FRED API — экономические данные США1
8
- # ============================================================
9
- API_KEY = "YOUR_FRED_API_KEY" # зарегистрируй на https://fred.stlouisfed.org/
10
  FRED_URL = "https://api.stlouisfed.org/fred/series/observations"
11
-
12
  INDICATORS = {
13
  "GDP": "GDP",
14
  "Inflation (CPI)": "CPIAUCSL",
@@ -16,63 +17,62 @@ INDICATORS = {
16
  "Interest Rate (Fed Funds)": "FEDFUNDS"
17
  }
18
 
19
- def fetch_fred_data(series_id, start="2024-01-01", end=None):
20
- if end is None:
21
- end = datetime.now().strftime("%Y-%m-%d")
 
 
 
 
 
 
 
 
 
 
22
  params = {
23
- "series_id": series_id,
24
- "api_key": API_KEY,
25
  "file_type": "json",
26
- "observation_start": start,
27
- "observation_end": end
28
  }
29
- r = requests.get(FRED_URL, params=params)
30
- data = r.json().get("observations", [])
31
  df = pd.DataFrame(data)
32
- if not df.empty:
33
- df["value"] = pd.to_numeric(df["value"], errors="coerce")
34
- return df
35
-
36
- # ============================================================
37
- # 2️⃣ Генерация сводки (LLM)
38
- # ============================================================
39
- generator = pipeline("text2text-generation", model="google/flan-t5-base")
40
 
41
- def generate_summary(topic):
42
- sid = INDICATORS.get(topic)
43
- df = fetch_fred_data(sid)
44
  if df.empty:
45
- return "⚠️ No data available for this indicator."
46
- last = df.tail(5)
47
- trend = last["value"].pct_change().mean() * 100
48
- context = f"Recent values of {topic}:\n{last[['date','value']].to_string(index=False)}\n\nAverage change: {trend:.2f}%"
49
- prompt = f"Provide an analytical summary of the trend:\n{context}"
50
- summary = generator(prompt, max_new_tokens=150)[0]["generated_text"]
51
- return summary, df
52
 
53
- # ============================================================
54
- # 3️⃣ Экспорт CSV → Power BI
55
- # ============================================================
56
- def export_csv(df, topic):
57
- filename = f"powerbi_{topic.replace(' ', '_').lower()}.csv"
58
- df.to_csv(filename, index=False)
59
- return filename
60
 
61
- # ============================================================
62
- # 4️⃣ Gradio UI
63
- # ============================================================
64
- with gr.Blocks(title="🏦 RAG Financial Analytics → Power BI") as app:
65
- gr.Markdown("## 🏦 Financial RAG: FRED API → LLM → Power BI")
66
 
67
- topic = gr.Dropdown(list(INDICATORS.keys()), label="Select Indicator", value="Inflation (CPI)")
68
- out_summary = gr.Textbox(label="Generated Summary", lines=8)
69
- out_file = gr.File(label="Power BI Export")
 
 
 
 
70
 
71
- def run_pipeline(topic):
72
- summary, df = generate_summary(topic)
73
- file_path = export_csv(df, topic)
74
- return summary, file_path
 
 
 
75
 
76
- gr.Button("Generate & Export").click(run_pipeline, inputs=topic, outputs=[out_summary, out_file])
 
77
 
78
- app.launch()
 
1
+ # app.py Financial RAG Dashboard
 
 
2
  import gradio as gr
3
+ import asyncio
4
+ import requests
5
+ import pandas as pd
6
+ from itertools import cycle
7
+ from transformers import pipeline
8
+ from datetime import datetime
9
 
10
+ # 🔧 Настройки
11
+ FRED_KEY = "YOUR_FRED_API_KEY"
 
 
12
  FRED_URL = "https://api.stlouisfed.org/fred/series/observations"
 
13
  INDICATORS = {
14
  "GDP": "GDP",
15
  "Inflation (CPI)": "CPIAUCSL",
 
17
  "Interest Rate (Fed Funds)": "FEDFUNDS"
18
  }
19
 
20
+ # 🧠 Модель генерации аналитики
21
+ generator = pipeline("text2text-generation", model="google/flan-t5-base")
22
+
23
+ # 🔁 Анимация “обработка...”
24
+ async def async_loader(update_fn, delay=0.15):
25
+ frames = cycle(["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"])
26
+ for frame in frames:
27
+ update_fn(f"💭 Fetching FRED data {frame}")
28
+ await asyncio.sleep(delay)
29
+
30
+ # 📈 Получение данных FRED
31
+ def fetch_data(indicator):
32
+ series = INDICATORS[indicator]
33
  params = {
34
+ "series_id": series,
35
+ "api_key": FRED_KEY,
36
  "file_type": "json",
37
+ "observation_start": "2024-01-01",
 
38
  }
39
+ data = requests.get(FRED_URL, params=params).json().get("observations", [])
 
40
  df = pd.DataFrame(data)
41
+ df["value"] = pd.to_numeric(df["value"], errors="coerce")
42
+ return df.tail(8)
 
 
 
 
 
 
43
 
44
+ # 🧩 Аналитика и экспорт
45
+ def generate_and_export(indicator):
46
+ df = fetch_data(indicator)
47
  if df.empty:
48
+ return "⚠️ No data found.", None
 
 
 
 
 
 
49
 
50
+ trend = df["value"].pct_change().mean() * 100
51
+ context = f"Recent {indicator} data:\n{df[['date','value']].to_string(index=False)}"
52
+ prompt = f"Analyze this economic indicator and summarize its recent trend:\n{context}\nAverage change: {trend:.2f}%"
53
+ summary = generator(prompt, max_new_tokens=120)[0]["generated_text"]
 
 
 
54
 
55
+ fname = f"powerbi_{indicator.lower().replace(' ','_')}.csv"
56
+ df.to_csv(fname, index=False)
57
+ return summary, fname
 
 
58
 
59
+ # 🧱 Gradio Interface
60
+ with gr.Blocks(theme=gr.themes.Soft(), title="🏦 Financial RAG → Power BI") as demo:
61
+ gr.Markdown(
62
+ "## 🏦 Financial RAG Dashboard\n"
63
+ "Автоматическая аналитика по банковским данным (FRED API) с экспортом в Power BI.\n\n"
64
+ "_Интерфейс с потоковой анимацией и аккуратной вёрсткой._"
65
+ )
66
 
67
+ with gr.Row():
68
+ with gr.Column(scale=1):
69
+ indicator = gr.Dropdown(list(INDICATORS.keys()), label="Выберите показатель", value="Inflation (CPI)")
70
+ btn = gr.Button("📊 Получить аналитику", variant="primary")
71
+ with gr.Column(scale=2):
72
+ summary = gr.Textbox(label="📈 Сводка аналитики", lines=8)
73
+ export_file = gr.File(label="📂 Файл для Power BI")
74
 
75
+ # Обработчик
76
+ btn.click(generate_and_export, inputs=indicator, outputs=[summary, export_file])
77
 
78
+ demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860)