Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,147 +1,115 @@
|
|
| 1 |
-
import io
|
| 2 |
-
import random
|
| 3 |
-
from typing import List, Tuple
|
| 4 |
-
|
| 5 |
-
import aiohttp
|
| 6 |
import panel as pn
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"message-circle": "https://discourse.holoviz.org/",
|
| 17 |
-
"brand-discord": "https://discord.gg/AXRHnJU6sP",
|
| 18 |
}
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
) -> Tuple[CLIPProcessor, CLIPModel]:
|
| 33 |
-
processor = CLIPProcessor.from_pretrained(processor_name)
|
| 34 |
-
model = CLIPModel.from_pretrained(model_name)
|
| 35 |
-
return processor, model
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
async def open_image_url(image_url: str) -> Image:
|
| 39 |
-
async with aiohttp.ClientSession() as session:
|
| 40 |
-
async with session.get(image_url) as resp:
|
| 41 |
-
return Image.open(io.BytesIO(await resp.read()))
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def get_similarity_scores(class_items: List[str], image: Image) -> List[float]:
|
| 45 |
-
processor, model = load_processor_model(
|
| 46 |
-
"openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32"
|
| 47 |
-
)
|
| 48 |
-
inputs = processor(
|
| 49 |
-
text=class_items,
|
| 50 |
-
images=[image],
|
| 51 |
-
return_tensors="pt", # pytorch tensors
|
| 52 |
-
)
|
| 53 |
-
outputs = model(**inputs)
|
| 54 |
-
logits_per_image = outputs.logits_per_image
|
| 55 |
-
class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy()
|
| 56 |
-
return class_likelihoods[0]
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
async def process_inputs(class_names: List[str], image_url: str):
|
| 60 |
-
"""
|
| 61 |
-
High level function that takes in the user inputs and returns the
|
| 62 |
-
classification results as panel objects.
|
| 63 |
-
"""
|
| 64 |
-
try:
|
| 65 |
-
main.disabled = True
|
| 66 |
-
if not image_url:
|
| 67 |
-
yield "##### ⚠️ Provide an image URL"
|
| 68 |
-
return
|
| 69 |
-
|
| 70 |
-
yield "##### ⚙ Fetching image and running model..."
|
| 71 |
-
try:
|
| 72 |
-
pil_img = await open_image_url(image_url)
|
| 73 |
-
img = pn.pane.Image(pil_img, height=400, align="center")
|
| 74 |
-
except Exception as e:
|
| 75 |
-
yield f"##### 😔 Something went wrong, please try a different URL!"
|
| 76 |
-
return
|
| 77 |
-
|
| 78 |
-
class_items = class_names.split(",")
|
| 79 |
-
class_likelihoods = get_similarity_scores(class_items, pil_img)
|
| 80 |
-
|
| 81 |
-
# build the results column
|
| 82 |
-
results = pn.Column("##### 🎉 Here are the results!", img)
|
| 83 |
-
|
| 84 |
-
for class_item, class_likelihood in zip(class_items, class_likelihoods):
|
| 85 |
-
row_label = pn.widgets.StaticText(
|
| 86 |
-
name=class_item.strip(), value=f"{class_likelihood:.2%}", align="center"
|
| 87 |
-
)
|
| 88 |
-
row_bar = pn.indicators.Progress(
|
| 89 |
-
value=int(class_likelihood * 100),
|
| 90 |
-
sizing_mode="stretch_width",
|
| 91 |
-
bar_color="secondary",
|
| 92 |
-
margin=(0, 10),
|
| 93 |
-
design=pn.theme.Material,
|
| 94 |
-
)
|
| 95 |
-
results.append(pn.Column(row_label, row_bar))
|
| 96 |
-
yield results
|
| 97 |
-
finally:
|
| 98 |
-
main.disabled = False
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
# create widgets
|
| 102 |
-
randomize_url = pn.widgets.Button(name="Randomize URL", align="end")
|
| 103 |
-
|
| 104 |
-
image_url = pn.widgets.TextInput(
|
| 105 |
-
name="Image URL to classify",
|
| 106 |
-
value=pn.bind(random_url, randomize_url),
|
| 107 |
-
)
|
| 108 |
-
class_names = pn.widgets.TextInput(
|
| 109 |
-
name="Comma separated class names",
|
| 110 |
-
placeholder="Enter possible class names, e.g. cat, dog",
|
| 111 |
-
value="cat, dog, parrot",
|
| 112 |
)
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
)
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
pn.bind(process_inputs, image_url=image_url, class_names=class_names),
|
| 123 |
-
height=600,
|
| 124 |
)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
footer_row.append(href_button)
|
| 132 |
-
footer_row.append(pn.Spacer())
|
| 133 |
-
|
| 134 |
-
# create dashboard
|
| 135 |
-
main = pn.WidgetBox(
|
| 136 |
-
input_widgets,
|
| 137 |
-
interactive_result,
|
| 138 |
-
footer_row,
|
| 139 |
)
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import panel as pn
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import hvplot.pandas
|
| 5 |
+
import asyncio
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
|
| 8 |
+
# --- Configuration ---
|
| 9 |
+
pn.extension('tabulator', sizing_mode="stretch_width")
|
| 10 |
+
|
| 11 |
+
# --- Dummy Data Generation ---
|
| 12 |
+
def generate_dummy_data(n_points=100):
|
| 13 |
+
"""Generates a DataFrame with simulated stock data."""
|
| 14 |
+
start_time = datetime.now() - timedelta(minutes=n_points)
|
| 15 |
+
time_index = pd.to_datetime([start_time + timedelta(minutes=i) for i in range(n_points)])
|
| 16 |
+
price = 100 + np.random.randn(n_points).cumsum()
|
| 17 |
+
return pd.DataFrame({'Time': time_index, 'Price': price}).set_index('Time')
|
| 18 |
+
|
| 19 |
+
def generate_ai_signal(current_price):
|
| 20 |
+
"""Simulates an AI model generating a trading signal."""
|
| 21 |
+
# Simple logic: buy if price is 'low', sell if 'high', hold otherwise.
|
| 22 |
+
if current_price % 10 < 3:
|
| 23 |
+
return 'BUY', 'green'
|
| 24 |
+
elif current_price % 10 > 7:
|
| 25 |
+
return 'SELL', 'red'
|
| 26 |
+
return 'HOLD', 'orange'
|
| 27 |
+
|
| 28 |
+
# --- Initial Data ---
|
| 29 |
+
data = generate_dummy_data()
|
| 30 |
+
current_signal, signal_color = generate_ai_signal(data['Price'].iloc[-1])
|
| 31 |
+
|
| 32 |
+
# --- Dashboard Components ---
|
| 33 |
+
|
| 34 |
+
# 1. User Controls
|
| 35 |
+
symbol_input = pn.widgets.TextInput(name='Stock Symbol', value='AI_STOCK', width=150)
|
| 36 |
+
update_interval = pn.widgets.IntSlider(name='Update Interval (s)', start=1, end=10, step=1, value=2, width=200)
|
| 37 |
+
|
| 38 |
+
# 2. AI Signal Indicator
|
| 39 |
+
signal_indicator = pn.indicators.Number(
|
| 40 |
+
name='AI Signal',
|
| 41 |
+
value=0, # Will be updated by text
|
| 42 |
+
format=f'{current_signal}',
|
| 43 |
+
font_size='36pt',
|
| 44 |
+
colors=[(999, signal_color)] # A single color based on the signal
|
| 45 |
+
)
|
| 46 |
|
| 47 |
+
# 3. Performance Metrics
|
| 48 |
+
metrics = {
|
| 49 |
+
'Metric': ['Win Rate', 'Profit Factor', 'Sharpe Ratio'],
|
| 50 |
+
'Value': ['62%', '1.85', '1.2'] # Dummy values
|
|
|
|
|
|
|
| 51 |
}
|
| 52 |
+
metrics_table = pn.widgets.Tabulator(pd.DataFrame(metrics), disabled=True, selectable=False)
|
| 53 |
+
|
| 54 |
+
# 4. Price Chart
|
| 55 |
+
price_chart = data.hvplot.line(
|
| 56 |
+
y='Price',
|
| 57 |
+
line_width=3,
|
| 58 |
+
height=400,
|
| 59 |
+
title="Live Stock Price",
|
| 60 |
+
xlabel="Time",
|
| 61 |
+
ylabel="Price",
|
| 62 |
+
responsive=True
|
| 63 |
+
).opts(
|
| 64 |
+
yformatter='%.2f'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
+
# --- Layout ---
|
| 68 |
+
sidebar = pn.Column(
|
| 69 |
+
"## ⚙️ Controls",
|
| 70 |
+
symbol_input,
|
| 71 |
+
update_interval,
|
| 72 |
+
"## 🤖 AI Analysis",
|
| 73 |
+
signal_indicator,
|
| 74 |
+
"## 📈 Performance",
|
| 75 |
+
metrics_table,
|
| 76 |
+
width=300
|
| 77 |
)
|
| 78 |
|
| 79 |
+
main_content = pn.Column(
|
| 80 |
+
price_chart
|
|
|
|
|
|
|
| 81 |
)
|
| 82 |
|
| 83 |
+
dashboard_layout = pn.template.FastListTemplate(
|
| 84 |
+
site="AI Trading Dashboard",
|
| 85 |
+
title=f"Live Analysis for {symbol_input.value}",
|
| 86 |
+
sidebar=[sidebar],
|
| 87 |
+
main=[main_content]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
)
|
| 89 |
|
| 90 |
+
# --- Interactivity & Live Updates ---
|
| 91 |
+
stream = hvplot.stream.Buffer(data, index=False, length=100)
|
| 92 |
+
price_chart.update(stream)
|
| 93 |
+
|
| 94 |
+
async def update_data():
|
| 95 |
+
"""Callback to simulate live data feed and update dashboard elements."""
|
| 96 |
+
while True:
|
| 97 |
+
await asyncio.sleep(update_interval.value)
|
| 98 |
+
|
| 99 |
+
# 1. Simulate new data point
|
| 100 |
+
last_time = data.index[-1]
|
| 101 |
+
new_time = last_time + timedelta(seconds=10) # Advance time
|
| 102 |
+
new_price = data['Price'].iloc[-1] + np.random.randn() * 0.5
|
| 103 |
+
new_data_point = pd.DataFrame([{'Time': new_time, 'Price': new_price}]).set_index('Time')
|
| 104 |
+
|
| 105 |
+
# 2. Update chart stream
|
| 106 |
+
stream.send(new_data_point)
|
| 107 |
+
|
| 108 |
+
# 3. Update AI Signal
|
| 109 |
+
new_signal, new_color = generate_ai_signal(new_price)
|
| 110 |
+
signal_indicator.format = f'{new_signal}' # Update text
|
| 111 |
+
signal_indicator.colors = [(999, new_color)] # Update color
|
| 112 |
+
|
| 113 |
+
# --- Add dashboard to the document and start the update loop ---
|
| 114 |
+
dashboard_layout.servable()
|
| 115 |
+
pn.state.onload(update_data)
|