Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -52,13 +52,13 @@ from PIL import Image
|
|
| 52 |
import io
|
| 53 |
|
| 54 |
MAX_MAX_NEW_TOKENS = 512
|
| 55 |
-
DEFAULT_MAX_NEW_TOKENS =
|
| 56 |
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "1024"))
|
| 57 |
|
| 58 |
DESCRIPTION = """\
|
| 59 |
# FinChat: Investing Q&A (Optimized for Speed)
|
| 60 |
This application delivers an interactive chat interface powered by a highly efficient, small AI model adapted for addressing investing and finance inquiries through specialized prompt engineering. It ensures rapid, reasoned responses to user queries. Duplicate this Space for customization or queue-free deployment.
|
| 61 |
-
<p>Running on CPU or GPU if available. Using Phi-2 model for faster inference. Inference is heavily optimized for responses in under 10 seconds for simple queries, with output limited to
|
| 62 |
"""
|
| 63 |
|
| 64 |
LICENSE = """\
|
|
@@ -146,26 +146,40 @@ def generate(
|
|
| 146 |
return
|
| 147 |
for ticker in tickers:
|
| 148 |
try:
|
| 149 |
-
data
|
|
|
|
| 150 |
if not data.empty:
|
| 151 |
-
if
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
initial = data['Adj Close'].iloc[0]
|
| 154 |
final = data['Adj Close'].iloc[-1]
|
| 155 |
start_date = data.index[0]
|
| 156 |
end_date = data.index[-1]
|
| 157 |
days = (end_date - start_date).days
|
| 158 |
years = days / 365.25
|
| 159 |
-
if years > 0:
|
| 160 |
cagr = ((final / initial) ** (1 / years) - 1) * 100
|
| 161 |
responses.append(f"- {ticker}: ~{cagr:.2f}%")
|
| 162 |
else:
|
| 163 |
-
responses.append(f"- {ticker}: Invalid period
|
| 164 |
else:
|
| 165 |
responses.append(f"- {ticker}: No historical data available between {start_year} and {end_year}.")
|
| 166 |
except Exception as e:
|
|
|
|
| 167 |
responses.append(f"- {ticker}: Error calculating CAGR - {str(e)}")
|
| 168 |
full_response = f"CAGR for the requested stocks from {start_year} to {end_year}:\n" + "\n".join(responses) + "\n- Represents average annual returns with compounding\n- Past performance not indicative of future results\n- Consult a financial advisor"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
logger.info("CAGR response generated.")
|
| 170 |
yield full_response
|
| 171 |
return
|
|
@@ -193,7 +207,7 @@ def generate(
|
|
| 193 |
yield "Error: Input is too long even after truncation. Please shorten your query."
|
| 194 |
return
|
| 195 |
|
| 196 |
-
# Generate response with sentence boundary checking
|
| 197 |
try:
|
| 198 |
response = ""
|
| 199 |
sentence_buffer = ""
|
|
@@ -211,10 +225,14 @@ def generate(
|
|
| 211 |
for chunk in stream:
|
| 212 |
delta = chunk["choices"][0]["delta"]
|
| 213 |
if "content" in delta and delta["content"] is not None:
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
# Approximate token count for the chunk
|
| 217 |
-
chunk_tokens = len(llm.tokenize(
|
| 218 |
token_count += chunk_tokens
|
| 219 |
|
| 220 |
# Check for sentence boundary
|
|
|
|
| 52 |
import io
|
| 53 |
|
| 54 |
MAX_MAX_NEW_TOKENS = 512
|
| 55 |
+
DEFAULT_MAX_NEW_TOKENS = 250
|
| 56 |
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "1024"))
|
| 57 |
|
| 58 |
DESCRIPTION = """\
|
| 59 |
# FinChat: Investing Q&A (Optimized for Speed)
|
| 60 |
This application delivers an interactive chat interface powered by a highly efficient, small AI model adapted for addressing investing and finance inquiries through specialized prompt engineering. It ensures rapid, reasoned responses to user queries. Duplicate this Space for customization or queue-free deployment.
|
| 61 |
+
<p>Running on CPU or GPU if available. Using Phi-2 model for faster inference. Inference is heavily optimized for responses in under 10 seconds for simple queries, with output limited to 250 tokens maximum. For longer responses, increase 'Max New Tokens' in Advanced Settings. Brief delays may occur in free-tier environments due to shared resources, but typical generation speeds are improved with the smaller model.</p>
|
| 62 |
"""
|
| 63 |
|
| 64 |
LICENSE = """\
|
|
|
|
| 146 |
return
|
| 147 |
for ticker in tickers:
|
| 148 |
try:
|
| 149 |
+
# Download data with adjusted close prices
|
| 150 |
+
data = yf.download(ticker, start=f"{start_year}-01-01", end=f"{end_year}-12-31", progress=False)
|
| 151 |
if not data.empty:
|
| 152 |
+
# Check if 'Adj Close' column exists
|
| 153 |
+
if 'Adj Close' not in data.columns:
|
| 154 |
+
responses.append(f"- {ticker}: Error - Adjusted Close price data not available.")
|
| 155 |
+
logger.error(f"No 'Adj Close' column for {ticker}.")
|
| 156 |
+
continue
|
| 157 |
+
# Ensure data is not MultiIndex for single ticker
|
| 158 |
initial = data['Adj Close'].iloc[0]
|
| 159 |
final = data['Adj Close'].iloc[-1]
|
| 160 |
start_date = data.index[0]
|
| 161 |
end_date = data.index[-1]
|
| 162 |
days = (end_date - start_date).days
|
| 163 |
years = days / 365.25
|
| 164 |
+
if years > 0 and pd.notna(initial) and pd.notna(final):
|
| 165 |
cagr = ((final / initial) ** (1 / years) - 1) * 100
|
| 166 |
responses.append(f"- {ticker}: ~{cagr:.2f}%")
|
| 167 |
else:
|
| 168 |
+
responses.append(f"- {ticker}: Invalid period or missing price data.")
|
| 169 |
else:
|
| 170 |
responses.append(f"- {ticker}: No historical data available between {start_year} and {end_year}.")
|
| 171 |
except Exception as e:
|
| 172 |
+
logger.error(f"Error calculating CAGR for {ticker}: {str(e)}")
|
| 173 |
responses.append(f"- {ticker}: Error calculating CAGR - {str(e)}")
|
| 174 |
full_response = f"CAGR for the requested stocks from {start_year} to {end_year}:\n" + "\n".join(responses) + "\n- Represents average annual returns with compounding\n- Past performance not indicative of future results\n- Consult a financial advisor"
|
| 175 |
+
full_response = re.sub(r'<\|im_end\>|</s>|\[END\]', '', full_response).strip() # Clean any trailing tokens
|
| 176 |
+
# Estimate token count to ensure response fits within max_new_tokens
|
| 177 |
+
response_tokens = len(llm.tokenize(full_response.encode("utf-8"), add_bos=False))
|
| 178 |
+
if response_tokens > max_new_tokens:
|
| 179 |
+
logger.warning(f"CAGR response tokens ({response_tokens}) exceed max_new_tokens ({max_new_tokens}). Truncating to first complete sentence.")
|
| 180 |
+
sentence_endings = ['.', '!', '?']
|
| 181 |
+
first_sentence_end = min([full_response.find(ending) + 1 for ending in sentence_endings if full_response.find(ending) != -1], default=len(full_response))
|
| 182 |
+
full_response = full_response[:first_sentence_end] if first_sentence_end > 0 else "Response truncated due to length; please increase Max New Tokens."
|
| 183 |
logger.info("CAGR response generated.")
|
| 184 |
yield full_response
|
| 185 |
return
|
|
|
|
| 207 |
yield "Error: Input is too long even after truncation. Please shorten your query."
|
| 208 |
return
|
| 209 |
|
| 210 |
+
# Generate response with sentence boundary checking and token cleanup
|
| 211 |
try:
|
| 212 |
response = ""
|
| 213 |
sentence_buffer = ""
|
|
|
|
| 225 |
for chunk in stream:
|
| 226 |
delta = chunk["choices"][0]["delta"]
|
| 227 |
if "content" in delta and delta["content"] is not None:
|
| 228 |
+
# Clean the chunk by removing <|im_end> or similar tokens
|
| 229 |
+
cleaned_chunk = re.sub(r'<\|im_end\>|</s>|\[END\]', '', delta["content"]).strip()
|
| 230 |
+
if not cleaned_chunk:
|
| 231 |
+
continue
|
| 232 |
+
sentence_buffer += cleaned_chunk
|
| 233 |
+
response += cleaned_chunk
|
| 234 |
# Approximate token count for the chunk
|
| 235 |
+
chunk_tokens = len(llm.tokenize(cleaned_chunk.encode("utf-8"), add_bos=False))
|
| 236 |
token_count += chunk_tokens
|
| 237 |
|
| 238 |
# Check for sentence boundary
|