Spaces:
Sleeping
Sleeping
QAway-to
commited on
Commit
·
ae4da3f
1
Parent(s):
90ba9ea
Base app.py interface v1.1
Browse files
app.py
CHANGED
|
@@ -1,78 +1,120 @@
|
|
| 1 |
-
# app.py — Financial RAG
|
| 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 |
-
|
|
|
|
|
|
|
| 12 |
FRED_URL = "https://api.stlouisfed.org/fred/series/observations"
|
|
|
|
| 13 |
INDICATORS = {
|
| 14 |
"GDP": "GDP",
|
| 15 |
"Inflation (CPI)": "CPIAUCSL",
|
| 16 |
"Unemployment Rate": "UNRATE",
|
| 17 |
-
"Interest Rate (Fed Funds)": "FEDFUNDS"
|
| 18 |
}
|
| 19 |
|
| 20 |
-
# 🧠 Модель генерации аналитики
|
| 21 |
generator = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
frames = cycle(["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"])
|
| 26 |
for frame in frames:
|
| 27 |
-
update_fn(f"💭 Fetching
|
| 28 |
await asyncio.sleep(delay)
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
params = {
|
| 34 |
-
"series_id":
|
| 35 |
-
"api_key":
|
| 36 |
"file_type": "json",
|
| 37 |
-
"observation_start":
|
| 38 |
}
|
| 39 |
-
|
|
|
|
| 40 |
df = pd.DataFrame(data)
|
|
|
|
|
|
|
| 41 |
df["value"] = pd.to_numeric(df["value"], errors="coerce")
|
| 42 |
-
return df.tail(
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
if df.empty:
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
-
#
|
|
|
|
|
|
|
| 60 |
with gr.Blocks(theme=gr.themes.Soft(), title="🏦 Financial RAG → Power BI") as demo:
|
| 61 |
gr.Markdown(
|
| 62 |
-
"## 🏦 Financial RAG
|
| 63 |
-
"
|
| 64 |
-
"
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
with gr.Row():
|
| 68 |
with gr.Column(scale=1):
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
# app.py — Financial RAG → Power BI
|
| 2 |
import gradio as gr
|
| 3 |
import asyncio
|
| 4 |
+
from itertools import cycle
|
| 5 |
+
from datetime import datetime
|
| 6 |
import requests
|
| 7 |
import pandas as pd
|
|
|
|
| 8 |
from transformers import pipeline
|
|
|
|
| 9 |
|
| 10 |
+
# ============================================================
|
| 11 |
+
# ⚙️ Конфигурация
|
| 12 |
+
# ============================================================
|
| 13 |
+
FRED_API_KEY = "YOUR_FRED_API_KEY" # зарегистрируй на https://fred.stlouisfed.org
|
| 14 |
FRED_URL = "https://api.stlouisfed.org/fred/series/observations"
|
| 15 |
+
|
| 16 |
INDICATORS = {
|
| 17 |
"GDP": "GDP",
|
| 18 |
"Inflation (CPI)": "CPIAUCSL",
|
| 19 |
"Unemployment Rate": "UNRATE",
|
| 20 |
+
"Interest Rate (Fed Funds)": "FEDFUNDS",
|
| 21 |
}
|
| 22 |
|
|
|
|
| 23 |
generator = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 24 |
|
| 25 |
+
# ============================================================
|
| 26 |
+
# 🌀 Асинхронная анимация "Loading..."
|
| 27 |
+
# ============================================================
|
| 28 |
+
async def async_loader(update_fn, delay=0.12):
|
| 29 |
frames = cycle(["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"])
|
| 30 |
for frame in frames:
|
| 31 |
+
update_fn(f"💭 Fetching financial data... {frame}")
|
| 32 |
await asyncio.sleep(delay)
|
| 33 |
|
| 34 |
+
# ============================================================
|
| 35 |
+
# 📈 Основная логика: загрузка, анализ, экспорт
|
| 36 |
+
# ============================================================
|
| 37 |
+
def get_fred_data(series_id, start="2024-01-01"):
|
| 38 |
params = {
|
| 39 |
+
"series_id": series_id,
|
| 40 |
+
"api_key": FRED_API_KEY,
|
| 41 |
"file_type": "json",
|
| 42 |
+
"observation_start": start,
|
| 43 |
}
|
| 44 |
+
r = requests.get(FRED_URL, params=params)
|
| 45 |
+
data = r.json().get("observations", [])
|
| 46 |
df = pd.DataFrame(data)
|
| 47 |
+
if df.empty:
|
| 48 |
+
return pd.DataFrame()
|
| 49 |
df["value"] = pd.to_numeric(df["value"], errors="coerce")
|
| 50 |
+
return df.tail(10)
|
| 51 |
|
| 52 |
+
def analyze_and_export(indicator_name, progress_text):
|
| 53 |
+
"""Потоковая функция, полностью в стиле MBTI-интерфейса."""
|
| 54 |
+
if not indicator_name:
|
| 55 |
+
yield "⚠️ Select indicator first.", "", progress_text
|
| 56 |
+
return
|
| 57 |
+
|
| 58 |
+
# шаг 1 — загрузка данных
|
| 59 |
+
yield "📡 Requesting latest data from FRED...", "⏳ Fetching...", "1/3"
|
| 60 |
+
series_id = INDICATORS[indicator_name]
|
| 61 |
+
df = get_fred_data(series_id)
|
| 62 |
if df.empty:
|
| 63 |
+
yield "⚠️ No data received.", "", "1/3"
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
# шаг 2 — подготовка контекста
|
| 67 |
+
recent = df.tail(5)
|
| 68 |
+
trend = recent["value"].pct_change().mean() * 100
|
| 69 |
+
context = f"Recent {indicator_name} values:\n{recent[['date','value']].to_string(index=False)}"
|
| 70 |
+
yield "📊 Data fetched successfully.", "💭 Generating analytical summary...", "2/3"
|
| 71 |
|
| 72 |
+
# шаг 3 — генерация аналитики
|
| 73 |
+
prompt = (
|
| 74 |
+
f"Analyze the following economic indicator data and describe the recent trend:\n"
|
| 75 |
+
f"{context}\nAverage change: {trend:.2f}%"
|
| 76 |
+
)
|
| 77 |
+
try:
|
| 78 |
+
response = generator(prompt, max_new_tokens=150)[0]["generated_text"]
|
| 79 |
+
except Exception as e:
|
| 80 |
+
response = f"⚠️ LLM generation error: {e}"
|
| 81 |
|
| 82 |
+
# шаг 4 — экспорт в CSV
|
| 83 |
+
filename = f"powerbi_{indicator_name.lower().replace(' ','_')}.csv"
|
| 84 |
+
df.to_csv(filename, index=False)
|
| 85 |
+
yield response, f"✅ Exported to {filename}", "3/3"
|
| 86 |
|
| 87 |
+
# ============================================================
|
| 88 |
+
# 🧱 Gradio UI (в том же формате, что MBTI)
|
| 89 |
+
# ============================================================
|
| 90 |
with gr.Blocks(theme=gr.themes.Soft(), title="🏦 Financial RAG → Power BI") as demo:
|
| 91 |
gr.Markdown(
|
| 92 |
+
"## 🏦 Financial RAG → Power BI\n"
|
| 93 |
+
"Получай аналитические сводки по банковским показателям (FRED API) "
|
| 94 |
+
"и экспортируй их прямо в Power BI CSV.\n\n"
|
| 95 |
+
"_Интерфейс в том же формате, что MBTI Interviewer._"
|
| 96 |
)
|
| 97 |
|
| 98 |
with gr.Row():
|
| 99 |
with gr.Column(scale=1):
|
| 100 |
+
indicator_in = gr.Dropdown(
|
| 101 |
+
choices=list(INDICATORS.keys()),
|
| 102 |
+
label="Выберите показатель",
|
| 103 |
+
value="Inflation (CPI)"
|
| 104 |
+
)
|
| 105 |
+
run_btn = gr.Button("📈 Сформировать отчёт", variant="primary")
|
| 106 |
|
| 107 |
+
with gr.Column(scale=1):
|
| 108 |
+
summary_out = gr.Textbox(label="📊 Аналитическая сводка", lines=7)
|
| 109 |
+
status_out = gr.Textbox(label="💬 Статус", lines=2)
|
| 110 |
+
progress_out = gr.Textbox(label="📊 Прогресс", value="0/3")
|
| 111 |
+
|
| 112 |
+
# Кнопка → потоковая функция
|
| 113 |
+
run_btn.click(
|
| 114 |
+
analyze_and_export,
|
| 115 |
+
inputs=[indicator_in, progress_out],
|
| 116 |
+
outputs=[summary_out, status_out, progress_out],
|
| 117 |
+
show_progress=True,
|
| 118 |
+
)
|
| 119 |
|
| 120 |
demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860)
|