GeminiAi commited on
Commit
54b2783
·
verified ·
1 Parent(s): f9611a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -53
app.py CHANGED
@@ -1,65 +1,115 @@
1
- import cv2
2
- import gradio as gr
3
  import torch
4
- from diffusers import StableDiffusionPipeline
5
  import numpy as np
6
- from transformers.utils import move_cache
7
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
8
-
9
- # Handle Transformers cache migration
10
- move_cache()
11
 
12
- # Initialize the Stable Diffusion pipeline
13
- model_id = "CompVis/stable-diffusion-v1-4"
14
- pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
15
- pipe = pipe.to("cuda")
16
 
17
- # Load text summarizer
18
- summarizer_model = "facebook/bart-large-cnn"
19
- tokenizer = AutoTokenizer.from_pretrained(summarizer_model)
20
- summarizer = AutoModelForSeq2SeqLM.from_pretrained(summarizer_model)
 
 
21
 
22
- # Create video from images using `OpenCV`
23
- def text_to_video(input_text, num_frames=10, fps=2):
24
- # Summarize the input text
25
- inputs = tokenizer(input_text, return_tensors="pt", truncation=True)
26
- summary_ids = summarizer.generate(inputs["input_ids"], max_length=30, min_length=5, length_penalty=2.0)
27
- prompt = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
28
 
29
- # Generate frames
30
- frames = []
31
- for i in range(num_frames):
32
- prompt_with_frame = f"{prompt}, frame {i+1}"
33
- image = pipe(prompt_with_frame).images[0]
34
- frames.append(np.array(image))
35
 
36
- # Save frames as a video
37
- height, width, layers = frames[0].shape
38
- video_path = "output.avi"
39
- out = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'XVID'), fps, (width, height))
40
 
41
- for frame in frames:
42
- out.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
43
- out.release()
 
 
 
 
 
 
 
 
44
 
45
- return video_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- # Gradio interface
48
- def generate_video(text, frames, fps):
49
- video_file = text_to_video(text, num_frames=frames, fps=fps)
50
- return video_file
 
51
 
52
- interface = gr.Interface(
53
- fn=generate_video,
54
- inputs=[
55
- gr.Textbox(label="Enter your text prompt"),
56
- gr.Slider(5, 30, value=10, step=1, label="Number of Frames"),
57
- gr.Slider(1, 10, value=2, step=1, label="Frames per Second (FPS)"),
58
- ],
59
- outputs=gr.Video(label="Generated Video"),
60
- title="Text-to-Video Generator",
61
- description="Enter a text prompt to generate a short video."
62
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- if __name__ == "__main__":
65
- interface.launch()
 
 
 
 
 
 
 
1
  import torch
2
+ import transformers
3
  import numpy as np
4
+ import gradio as gr
5
+ import openai
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ import matplotlib.pyplot as plt
8
+ from datetime import datetime, timedelta
9
 
10
+ # Load Hugging Face model for financial insights generation
11
+ generator = transformers.pipeline("text-generation", model="gpt2")
 
 
12
 
13
+ # Sample function for fetching stock market data (you can use libraries like yfinance or Alpha Vantage)
14
+ def get_stock_data(symbol, start_date, end_date):
15
+ # This is just a placeholder. In production, use an API to get actual stock data
16
+ dates = np.array([start_date + timedelta(days=i) for i in range((end_date - start_date).days)])
17
+ prices = np.sin(np.linspace(0, 20, len(dates))) * 100 + 1000 # Placeholder for stock prices
18
+ return dates, prices
19
 
20
+ # Preprocessing stock data for prediction
21
+ def preprocess_data(prices):
22
+ scaler = MinMaxScaler(feature_range=(0, 1))
23
+ prices_scaled = scaler.fit_transform(prices.reshape(-1, 1))
24
+ return scaler, prices_scaled
 
25
 
26
+ # LSTM-based deep learning model for stock price prediction
27
+ class StockPredictor(torch.nn.Module):
28
+ def __init__(self, input_size=1, hidden_size=50, num_layers=1):
29
+ super(StockPredictor, self).__init__()
30
+ self.lstm = torch.nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
31
+ self.fc = torch.nn.Linear(hidden_size, 1)
32
 
33
+ def forward(self, x):
34
+ out, _ = self.lstm(x)
35
+ out = self.fc(out[:, -1, :])
36
+ return out
37
 
38
+ # Function to train the model on historical stock data
39
+ def train_model(prices_scaled):
40
+ model = StockPredictor()
41
+ criterion = torch.nn.MSELoss()
42
+ optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
43
+
44
+ # Prepare data for training
45
+ X_train, y_train = [], []
46
+ for i in range(len(prices_scaled) - 1):
47
+ X_train.append(prices_scaled[i:i+10]) # Using the last 10 days to predict next day's price
48
+ y_train.append(prices_scaled[i+10])
49
 
50
+ X_train = torch.tensor(np.array(X_train), dtype=torch.float32)
51
+ y_train = torch.tensor(np.array(y_train), dtype=torch.float32)
52
+
53
+ # Train the model
54
+ for epoch in range(100):
55
+ model.train()
56
+ optimizer.zero_grad()
57
+ outputs = model(X_train)
58
+ loss = criterion(outputs, y_train)
59
+ loss.backward()
60
+ optimizer.step()
61
+
62
+ return model
63
+
64
+ # Predict future stock prices
65
+ def predict_stock(model, scaler, input_data):
66
+ model.eval()
67
+ with torch.no_grad():
68
+ predictions = model(torch.tensor(input_data, dtype=torch.float32))
69
+ return scaler.inverse_transform(predictions.detach().numpy())
70
 
71
+ # Generate financial insights using Hugging Face's GPT model
72
+ def generate_financial_insight(stock_symbol):
73
+ prompt = f"Generate a detailed financial report for the stock symbol {stock_symbol} based on recent market trends."
74
+ response = generator(prompt, max_length=150, num_return_sequences=1)
75
+ return response[0]['generated_text']
76
 
77
+ # Gradio interface function
78
+ def financial_advisor(symbol):
79
+ start_date = datetime.now() - timedelta(days=365) # Last year data
80
+ end_date = datetime.now()
81
+
82
+ # Get stock data (for simplicity, using dummy data here)
83
+ dates, prices = get_stock_data(symbol, start_date, end_date)
84
+
85
+ # Preprocess data for prediction
86
+ scaler, prices_scaled = preprocess_data(prices)
87
+
88
+ # Train the model on historical data
89
+ model = train_model(prices_scaled)
90
+
91
+ # Predict future prices (for simplicity, predicting the next 30 days)
92
+ future_data = prices_scaled[-10:].reshape(1, 10, 1)
93
+ predictions = predict_stock(model, scaler, future_data)
94
+
95
+ # Generate financial insights
96
+ insight = generate_financial_insight(symbol)
97
+
98
+ # Plot predicted prices
99
+ plt.plot(dates, prices, label="Historical Prices")
100
+ predicted_dates = [dates[-1] + timedelta(days=i) for i in range(1, 31)]
101
+ plt.plot(predicted_dates, predictions, label="Predicted Prices", linestyle="--")
102
+ plt.xlabel('Date')
103
+ plt.ylabel('Price')
104
+ plt.legend()
105
+ plt.xticks(rotation=45)
106
+
107
+ # Return results to display in Gradio
108
+ return plt.gcf(), f"Financial Insight for {symbol}: {insight}"
109
 
110
+ # Launch Gradio interface
111
+ gr.Interface(
112
+ fn=financial_advisor,
113
+ inputs=[gr.Textbox(label="Stock Symbol", placeholder="Enter Stock Symbol (e.g., AAPL)")],
114
+ outputs=[gr.Plot(), gr.Textbox()]
115
+ ).launch()