|
import gradio as gr |
|
import pandas as pd |
|
import numpy as np |
|
import requests |
|
from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration |
|
from stable_baselines3 import PPO |
|
import gym |
|
from gym import spaces |
|
from stable_baselines3.common.vec_env import DummyVecEnv |
|
import plotly.graph_objects as go |
|
|
|
|
|
GROQ_API_KEY = "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" |
|
groq_api_url = "https://api.groq.com/v1/traffic/optimize" |
|
|
|
headers = { |
|
'Authorization': f'Bearer {GROQ_API_KEY}', |
|
} |
|
|
|
|
|
def load_traffic_data(file_path): |
|
data = pd.read_csv(file_path) |
|
return data |
|
|
|
|
|
def get_optimization_strategy(traffic_data): |
|
traffic_data = [int(x) if isinstance(x, np.int64) else x for x in traffic_data] |
|
response = requests.post(groq_api_url, json={'traffic_data': traffic_data}, headers=headers) |
|
if response.status_code == 200: |
|
optimization_strategy = response.json() |
|
return optimization_strategy |
|
else: |
|
return f"Error: {response.status_code}, {response.text}" |
|
|
|
|
|
class TrafficEnv(gym.Env): |
|
def __init__(self, traffic_data): |
|
super(TrafficEnv, self).__init__() |
|
|
|
self.action_space = spaces.Discrete(3) |
|
self.observation_space = spaces.Box(low=0, high=50, shape=(5,), dtype=np.float32) |
|
self.current_state = np.zeros(5) |
|
self.traffic_data = traffic_data |
|
|
|
def reset(self): |
|
self.current_state = np.array(self.traffic_data.iloc[0, 3:7], dtype=np.float32) |
|
return self.current_state |
|
|
|
def step(self, action): |
|
if action == 0: |
|
self.current_state = self.current_state - np.random.randint(1, 5, size=self.current_state.shape) |
|
elif action == 1: |
|
self.current_state = self.current_state |
|
elif action == 2: |
|
self.current_state = self.current_state + np.random.randint(1, 5, size=self.current_state.shape) |
|
self.current_state = np.clip(self.current_state, 0, None) |
|
reward = -np.sum(self.current_state) |
|
done = np.sum(self.current_state) < 50 |
|
return self.current_state, reward, done, {} |
|
|
|
def create_environment(traffic_data): |
|
return DummyVecEnv([lambda: TrafficEnv(traffic_data)]) |
|
|
|
|
|
def visualize_traffic_flow(traffic_data): |
|
locations = ['CarCount', 'BikeCount', 'BusCount', 'TruckCount'] |
|
traffic_flow = traffic_data.iloc[0, 3:7] |
|
fig = go.Figure(data=[go.Bar(x=locations, y=traffic_flow)]) |
|
fig.update_layout(title='Real-Time Traffic Flow', xaxis_title='Location', yaxis_title='Traffic Volume') |
|
return fig |
|
|
|
|
|
def rag_based_optimization(query): |
|
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") |
|
model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq") |
|
|
|
inputs = tokenizer(query, return_tensors="pt") |
|
generated_ids = model.generate(input_ids=inputs['input_ids']) |
|
generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) |
|
return generated_text |
|
|
|
|
|
def optimize_traffic(traffic_file, query): |
|
|
|
traffic_data = load_traffic_data(traffic_file.name) |
|
|
|
|
|
optimization_strategy = get_optimization_strategy(traffic_data.iloc[0, 3:7].values.tolist()) |
|
|
|
|
|
traffic_fig = visualize_traffic_flow(traffic_data) |
|
|
|
|
|
rag_strategy = rag_based_optimization(query) |
|
|
|
return optimization_strategy, traffic_fig, rag_strategy |
|
|
|
|
|
iface = gr.Interface( |
|
fn=optimize_traffic, |
|
inputs=[ |
|
gr.File(label="Upload Traffic Data CSV"), |
|
gr.Textbox(label="Enter Optimization Query", value="Optimize traffic flow for downtown area.") |
|
], |
|
outputs=[ |
|
gr.JSON(label="Optimization Strategy from Groq API"), |
|
gr.Plot(label="Traffic Flow Visualization"), |
|
gr.Textbox(label="RAG-based Optimization Strategy") |
|
], |
|
live=True, |
|
title="Traffic Optimization App", |
|
description="This app optimizes traffic flow using RL, Groq API, and RAG model-based optimization strategies." |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|
|
|