Spaces:
Sleeping
Sleeping
Download backend/llm_vision_analysis.py from PROSTLE/StockSense-AI: direct link, hf CLI and curl.
- Browser
- Download file 3.37 kB
-
https://huggingface.co/spaces/PROSTLE/StockSense-AI/resolve/main/backend/llm_vision_analysis.py
- Command line
-
hf download hf://spaces/PROSTLE/StockSense-AI/backend/llm_vision_analysis.py
-
curl -L -o llm_vision_analysis.py https://huggingface.co/spaces/PROSTLE/StockSense-AI/resolve/main/backend/llm_vision_analysis.py
3.37 kB
| import os | |
| import io | |
| import json | |
| import base64 | |
| import matplotlib.pyplot as plt | |
| import pandas as pd | |
| from datetime import datetime | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| from llm_proxy import get_llm_client | |
| class LLMVisionEngine: | |
| def __init__(self): | |
| self.proxy = get_llm_client() | |
| def analyze_chart(self, ticker: str, df: pd.DataFrame) -> dict: | |
| """ | |
| Generates a chart image and asks the LLM to interpret the patterns. | |
| """ | |
| if self.proxy.mode == "none": | |
| return {"error": "LLM Proxy unavailable"} | |
| # 1. Generate the Chart | |
| img_bytes = self._generate_chart_bytes(ticker, df) | |
| # 2. Prepare Prompt | |
| prompt = f""" | |
| Analyze this stock chart for {ticker}. | |
| Identify key technical patterns (e.g., support/resistance, breakouts, trendlines). | |
| Predict the likely direction for the next 5-10 bars. | |
| Respond ONLY with this JSON format: | |
| {{ | |
| "direction": "bullish|bearish|neutral", | |
| "score": <float -0.99 to 0.99>, | |
| "reasoning": "<one sentence analysis of visual patterns>", | |
| "patterns": ["pattern1", "pattern2"] | |
| }} | |
| """ | |
| try: | |
| # 3. Send to Proxy | |
| text = self.proxy.generate_content(prompt, image_bytes=img_bytes) | |
| text = text.strip() | |
| if "```" in text: | |
| parts = text.split("```") | |
| if len(parts) >= 2: | |
| text = parts[1] | |
| if text.startswith("json"): | |
| text = text[4:] | |
| text = text.strip() | |
| prediction = json.loads(text) | |
| prediction["source"] = f"llm_proxy_vision/{self.proxy.mode}" | |
| # Ensure score is rounded and clamped | |
| raw_score = float(prediction.get("score", 0.0)) | |
| prediction["score"] = round(max(-0.99, min(0.99, raw_score)), 3) | |
| return prediction | |
| except Exception as e: | |
| print(f"[Vision] Engine error: {e}") | |
| return {"error": str(e)} | |
| def _generate_chart_bytes(self, ticker: str, df: pd.DataFrame) -> bytes: | |
| """Helper to create a matplotlib chart and return raw bytes.""" | |
| plt.figure(figsize=(10, 6)) | |
| # Plot Close price | |
| plt.plot(df.index, df['Close'], label='Close', color='#2196F3', linewidth=2) | |
| # Add a few key indicators if present | |
| if 'SMA_20' in df.columns: | |
| plt.plot(df.index, df['SMA_20'], label='SMA 20', color='#FF9800', linestyle='--', alpha=0.7) | |
| if 'SMA_50' in df.columns: | |
| plt.plot(df.index, df['SMA_50'], label='SMA 50', color='#E91E63', linestyle='--', alpha=0.7) | |
| plt.title(f"{ticker} - Market Analysis Graph", color='white', fontsize=14) | |
| plt.grid(True, alpha=0.2) | |
| plt.legend() | |
| # Style for Dark Mode (matching UI) | |
| plt.gca().set_facecolor('#0f172a') | |
| plt.gcf().set_facecolor('#0f172a') | |
| plt.tick_params(colors='white') | |
| for spine in plt.gca().spines.values(): | |
| spine.set_color('#334155') | |
| # Save to buffer | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', bbox_inches='tight', facecolor='#0f172a') | |
| plt.close() | |
| return buf.getvalue() | |