Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- pipeline/analyst.py +89 -8
- web_app/app.py +20 -7
pipeline/analyst.py
CHANGED
|
@@ -14,6 +14,8 @@ from typing import Dict, List, Optional
|
|
| 14 |
|
| 15 |
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
from config import GEMINI_API_KEY, CLAUDE_API_KEY, GEMINI_MODEL, CLAUDE_MODEL, OPENAI_API_KEY, OPENAI_MODEL, GROQ_API_KEY, GROQ_MODEL, NVIDIA_API_KEY, NVIDIA_MODEL
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
# ββ Formatting helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -41,6 +43,36 @@ def _money(v, currency="INR", units="Crores"):
|
|
| 41 |
return f"{sym}{v/1000:,.2f}B"
|
| 42 |
return f"{sym}{v:,.2f}M"
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# ββ Context builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
|
|
@@ -420,6 +452,51 @@ def _claude_generate(context: str, section: str, log_fn=None) -> str:
|
|
| 420 |
return None
|
| 421 |
|
| 422 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
# ββ Parse structured sections βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 424 |
|
| 425 |
def _parse_swot(text: str) -> Dict[str, List[str]]:
|
|
@@ -493,13 +570,14 @@ def generate_narrative(
|
|
| 493 |
use_openai = "openai" in models and bool(OPENAI_API_KEY)
|
| 494 |
use_groq = "groq" in models and bool(GROQ_API_KEY)
|
| 495 |
use_nvidia = "nvidia" in models and bool(NVIDIA_API_KEY)
|
|
|
|
| 496 |
|
| 497 |
-
if not any([use_gemini, use_claude, use_openai, use_groq, use_nvidia]):
|
| 498 |
log("No AI models configured. Running data-only analysis (no narrative).")
|
| 499 |
return _empty_narrative()
|
| 500 |
|
| 501 |
context = _build_context(data, meta)
|
| 502 |
-
active = [m for m, ok in [("Gemini",use_gemini),("Claude",use_claude),("ChatGPT",use_openai),("Groq",use_groq),("NVIDIA",use_nvidia)] if ok]
|
| 503 |
log(f"Generating AI narrative ({', '.join(active)}) ...")
|
| 504 |
|
| 505 |
def _synthesize_drafts(section: str, drafts: Dict[str, str]) -> str:
|
|
@@ -511,6 +589,7 @@ def generate_narrative(
|
|
| 511 |
elif use_nvidia: synthesizer = ("NVIDIA", _nvidia_generate)
|
| 512 |
elif use_gemini: synthesizer = ("Gemini", _gemini_generate)
|
| 513 |
elif use_groq: synthesizer = ("Groq", _groq_generate)
|
|
|
|
| 514 |
|
| 515 |
if not synthesizer:
|
| 516 |
return list(drafts.values())[0]
|
|
@@ -540,12 +619,14 @@ def generate_narrative(
|
|
| 540 |
|
| 541 |
def gen(section: str) -> str:
|
| 542 |
tasks = {}
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
if
|
| 546 |
-
if
|
| 547 |
-
if
|
| 548 |
-
if
|
|
|
|
|
|
|
| 549 |
|
| 550 |
drafts = {}
|
| 551 |
for future in concurrent.futures.as_completed(tasks):
|
|
|
|
| 14 |
|
| 15 |
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
from config import GEMINI_API_KEY, CLAUDE_API_KEY, GEMINI_MODEL, CLAUDE_MODEL, OPENAI_API_KEY, OPENAI_MODEL, GROQ_API_KEY, GROQ_MODEL, NVIDIA_API_KEY, NVIDIA_MODEL
|
| 17 |
+
import config
|
| 18 |
+
import time
|
| 19 |
|
| 20 |
|
| 21 |
# ββ Formatting helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 43 |
return f"{sym}{v/1000:,.2f}B"
|
| 44 |
return f"{sym}{v:,.2f}M"
|
| 45 |
|
| 46 |
+
# ββ Retry Wrapper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
|
| 48 |
+
def _with_retries(func, log_fn=None, max_retries=3, backoff_factor=2):
|
| 49 |
+
"""Wrap an API call with exponential backoff for rate limits."""
|
| 50 |
+
def wrapper(*args, **kwargs):
|
| 51 |
+
retries = 0
|
| 52 |
+
while retries <= max_retries:
|
| 53 |
+
try:
|
| 54 |
+
res = func(*args, **kwargs)
|
| 55 |
+
if res:
|
| 56 |
+
return res
|
| 57 |
+
# If None returned (handled internally without raising), assume fail
|
| 58 |
+
except Exception as e:
|
| 59 |
+
err_str = str(e).lower()
|
| 60 |
+
if "429" in err_str or "too many requests" in err_str or "quota" in err_str:
|
| 61 |
+
if retries == max_retries:
|
| 62 |
+
if log_fn: log_fn(f"[Error] Max retries reached for {func.__name__}")
|
| 63 |
+
return None
|
| 64 |
+
sleep_time = backoff_factor ** retries
|
| 65 |
+
if log_fn: log_fn(f"[Warning] Rate limited in {func.__name__}, retrying in {sleep_time}s...")
|
| 66 |
+
time.sleep(sleep_time)
|
| 67 |
+
retries += 1
|
| 68 |
+
continue
|
| 69 |
+
else:
|
| 70 |
+
if log_fn: log_fn(f"[Error] {func.__name__} failed: {e}")
|
| 71 |
+
return None
|
| 72 |
+
return None
|
| 73 |
+
return None
|
| 74 |
+
return wrapper
|
| 75 |
+
|
| 76 |
|
| 77 |
# ββ Context builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 78 |
|
|
|
|
| 452 |
return None
|
| 453 |
|
| 454 |
|
| 455 |
+
# ββ Hugging Face (DeepSeek) βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 456 |
+
|
| 457 |
+
def _hf_generate(context: str, section: str, log_fn=None) -> Optional[str]:
|
| 458 |
+
"""Generate using Hugging Face Inference API (DeepSeek)."""
|
| 459 |
+
hf_key = getattr(config, "HF_API_KEY", "")
|
| 460 |
+
if not hf_key:
|
| 461 |
+
return None
|
| 462 |
+
|
| 463 |
+
try:
|
| 464 |
+
import requests
|
| 465 |
+
url = "https://api-inference.huggingface.co/models/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"
|
| 466 |
+
headers = {
|
| 467 |
+
"Authorization": f"Bearer {hf_key}",
|
| 468 |
+
"Content-Type": "application/json"
|
| 469 |
+
}
|
| 470 |
+
prompt = f"FINANCIAL DATA:\n{context}\n\nTASK:\n{SECTION_PROMPTS[section]}\n\nRespond ONLY with the requested analysis text."
|
| 471 |
+
payload = {
|
| 472 |
+
"inputs": f"<|system|>{SYSTEM_PROMPT}<|user|>{prompt}<|assistant|>",
|
| 473 |
+
"parameters": {
|
| 474 |
+
"max_new_tokens": 1024,
|
| 475 |
+
"return_full_text": False,
|
| 476 |
+
"temperature": 0.2
|
| 477 |
+
}
|
| 478 |
+
}
|
| 479 |
+
r = requests.post(url, headers=headers, json=payload, timeout=40)
|
| 480 |
+
if r.status_code == 200:
|
| 481 |
+
res = r.json()
|
| 482 |
+
if isinstance(res, list) and len(res) > 0:
|
| 483 |
+
text = res[0].get("generated_text", "")
|
| 484 |
+
# DeepSeek-R1 sometimes includes <think> tags, let's strip them
|
| 485 |
+
import re
|
| 486 |
+
text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
|
| 487 |
+
return text
|
| 488 |
+
elif r.status_code == 429:
|
| 489 |
+
raise Exception("429 Too Many Requests")
|
| 490 |
+
else:
|
| 491 |
+
if log_fn: log_fn(f"[Warning] HF DeepSeek failed {r.status_code}: {r.text[:80]}")
|
| 492 |
+
return None
|
| 493 |
+
except Exception as e:
|
| 494 |
+
if log_fn: log_fn(f"[Warning] HF DeepSeek failed for {section}: {str(e)[:80]}")
|
| 495 |
+
# Re-raise so the retry wrapper catches 429s
|
| 496 |
+
raise e
|
| 497 |
+
return None
|
| 498 |
+
|
| 499 |
+
|
| 500 |
# ββ Parse structured sections βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 501 |
|
| 502 |
def _parse_swot(text: str) -> Dict[str, List[str]]:
|
|
|
|
| 570 |
use_openai = "openai" in models and bool(OPENAI_API_KEY)
|
| 571 |
use_groq = "groq" in models and bool(GROQ_API_KEY)
|
| 572 |
use_nvidia = "nvidia" in models and bool(NVIDIA_API_KEY)
|
| 573 |
+
use_hf = "huggingface" in models and bool(getattr(config, "HF_API_KEY", ""))
|
| 574 |
|
| 575 |
+
if not any([use_gemini, use_claude, use_openai, use_groq, use_nvidia, use_hf]):
|
| 576 |
log("No AI models configured. Running data-only analysis (no narrative).")
|
| 577 |
return _empty_narrative()
|
| 578 |
|
| 579 |
context = _build_context(data, meta)
|
| 580 |
+
active = [m for m, ok in [("Gemini",use_gemini),("Claude",use_claude),("ChatGPT",use_openai),("Groq",use_groq),("NVIDIA",use_nvidia),("HF-DeepSeek",use_hf)] if ok]
|
| 581 |
log(f"Generating AI narrative ({', '.join(active)}) ...")
|
| 582 |
|
| 583 |
def _synthesize_drafts(section: str, drafts: Dict[str, str]) -> str:
|
|
|
|
| 589 |
elif use_nvidia: synthesizer = ("NVIDIA", _nvidia_generate)
|
| 590 |
elif use_gemini: synthesizer = ("Gemini", _gemini_generate)
|
| 591 |
elif use_groq: synthesizer = ("Groq", _groq_generate)
|
| 592 |
+
elif use_hf: synthesizer = ("HF-DeepSeek", _hf_generate)
|
| 593 |
|
| 594 |
if not synthesizer:
|
| 595 |
return list(drafts.values())[0]
|
|
|
|
| 619 |
|
| 620 |
def gen(section: str) -> str:
|
| 621 |
tasks = {}
|
| 622 |
+
# Max workers set to 3 to avoid extreme rate limits on free tiers (like Groq's 30 RPM)
|
| 623 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
| 624 |
+
if use_gemini: tasks[executor.submit(_with_retries(_gemini_generate, log_fn), context, section)] = "Gemini"
|
| 625 |
+
if use_claude: tasks[executor.submit(_with_retries(_claude_generate, log_fn), context, section)] = "Claude"
|
| 626 |
+
if use_openai: tasks[executor.submit(_with_retries(_openai_generate, log_fn), context, section)] = "ChatGPT"
|
| 627 |
+
if use_groq: tasks[executor.submit(_with_retries(_groq_generate, log_fn), context, section)] = "Groq"
|
| 628 |
+
if use_nvidia: tasks[executor.submit(_with_retries(_nvidia_generate, log_fn), context, section)] = "NVIDIA"
|
| 629 |
+
if use_hf: tasks[executor.submit(_with_retries(_hf_generate, log_fn), context, section)] = "HF-DeepSeek"
|
| 630 |
|
| 631 |
drafts = {}
|
| 632 |
for future in concurrent.futures.as_completed(tasks):
|
web_app/app.py
CHANGED
|
@@ -174,13 +174,18 @@ st.sidebar.markdown("""
|
|
| 174 |
**Hugging Face** *(Serverless API)*
|
| 175 |
<a href='https://huggingface.co/settings/tokens' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key β huggingface.co</a>
|
| 176 |
""", unsafe_allow_html=True)
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
# ββ PAID OPTIONS βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 186 |
st.sidebar.markdown("""
|
|
@@ -288,6 +293,14 @@ with col1:
|
|
| 288 |
help="Free. Get key at console.groq.com"
|
| 289 |
):
|
| 290 |
engines.append("groq")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
if st.checkbox(
|
| 293 |
"π Gemini 2.0 Flash (Google)",
|
|
|
|
| 174 |
**Hugging Face** *(Serverless API)*
|
| 175 |
<a href='https://huggingface.co/settings/tokens' target='_blank' style='font-size:0.75rem;color:#34D399;'>Get free key β huggingface.co</a>
|
| 176 |
""", unsafe_allow_html=True)
|
| 177 |
+
|
| 178 |
+
_env_hf = os.environ.get("HF_API_KEY", "")
|
| 179 |
+
if _env_hf:
|
| 180 |
+
hf_key = _env_hf
|
| 181 |
+
st.sidebar.success("β
HF Key securely loaded from server secrets.")
|
| 182 |
+
else:
|
| 183 |
+
hf_key = st.sidebar.text_input(
|
| 184 |
+
"Hugging Face API Key", type="password",
|
| 185 |
+
placeholder="hf_β¦",
|
| 186 |
+
help="Used for intelligent peer selection and DeepSeek analysis.",
|
| 187 |
+
key="inp_hf"
|
| 188 |
+
)
|
| 189 |
|
| 190 |
# ββ PAID OPTIONS βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 191 |
st.sidebar.markdown("""
|
|
|
|
| 293 |
help="Free. Get key at console.groq.com"
|
| 294 |
):
|
| 295 |
engines.append("groq")
|
| 296 |
+
|
| 297 |
+
if st.checkbox(
|
| 298 |
+
"π Hugging Face β DeepSeek-R1",
|
| 299 |
+
value=bool(hf_key),
|
| 300 |
+
disabled=not hf_key,
|
| 301 |
+
help="Free via Hugging Face Inference API"
|
| 302 |
+
):
|
| 303 |
+
engines.append("huggingface")
|
| 304 |
|
| 305 |
if st.checkbox(
|
| 306 |
"π Gemini 2.0 Flash (Google)",
|