Spaces:
Running
Running
File size: 13,098 Bytes
6c79bb3 3cba118 6c79bb3 1a2d948 6c79bb3 8449cd9 1a2d948 6c79bb3 1a2d948 8449cd9 1a2d948 8449cd9 6c79bb3 d509664 6c79bb3 8449cd9 6c79bb3 a08a87e 6c79bb3 3cba118 a08a87e 6c79bb3 1a4a0f1 3cba118 6c79bb3 bcde89d d72a9fe 6c79bb3 3cba118 6c79bb3 c83a1d2 6c79bb3 1a4a0f1 6c79bb3 1a4a0f1 6c79bb3 1a4a0f1 6c79bb3 1a4a0f1 6c79bb3 1a4a0f1 6c79bb3 1a4a0f1 6c79bb3 4a913b0 6c79bb3 d509664 d72a9fe d509664 d72a9fe d509664 6c79bb3 4a913b0 6c79bb3 cc8c4e5 6c79bb3 d72a9fe 6c79bb3 1a4a0f1 6c79bb3 d509664 3cba118 6c79bb3 bcceadc 6c79bb3 1a2d948 6c79bb3 3c075f5 d509664 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
import gradio as gr
import pandas as pd
import numpy as np
import random
import time
import os
from openai import OpenAI
from dotenv import load_dotenv
import requests
from PIL import Image
load_dotenv("saathi.env")
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
def put_df2use(html):
df = pd.read_html(html)[0]
return df
def make_msg_chunk_ai(history,team_dropdown,all_teams_df,batting_team,batting_score,chase):
#hit flask here for system message with flag
req_params = {'flag':os.environ.get("FLAG")}
url = os.environ["FLASK_AI_PROMPT"]
response = requests.post(url, json=req_params)
full_data = response.json()
system_message=full_data['ai_data']
print("Got Ai Data : ",system_message,"\n====SYSTEM MESSAGE")
temp_df = all_teams_df[all_teams_df["team_id"]==team_dropdown]
temp_df = temp_df.drop(["team_id","player_code"],axis=1)
cur_tem_selection = temp_df[["player_name","role_type","team"]]
updated_system_message = system_message + f"\n Here is the senario by user \n First Batting team ->{batting_team} \n Batting Score ->{batting_score} \n Chase by second Team -> {chase} \n\n *Fantasy Team Selected By User : \n\n {cur_tem_selection.to_string(index=False)}\n\n--"
ai_msg = [{"role": "system", "content": updated_system_message}]
for chat in history:
user_m,bot_m=chat
if user_m:
val = {"role": "user", "content": user_m}
ai_msg.append(val)
if bot_m:
val = {"role": "assistant", "content": bot_m}
ai_msg.append(val)
return ai_msg
def user(user_message, history):
return "", history + [[user_message, None]]
def bot(history,team_dropdown,all_teams_df,batting_team,batting_score,chase):
print(len(history),"====This is history")
bot_templete = make_msg_chunk_ai(history,team_dropdown,all_teams_df,batting_team,batting_score,chase)
print("Made bot templete")
stream = client.chat.completions.create(
model="gpt-4o",
messages=bot_templete,
stream=True)
history[-1][1] = ""
for chunk in stream:
if chunk.choices[0].delta.content is not None:
history[-1][1]+=chunk.choices[0].delta.content
time.sleep(0.09)
print(history)
yield history
def save_like_data(like_data: gr.LikeData):
print(like_data.liked,like_data.value,like_data.index)
def activate_chat(chat,user_btn,clear_btn):
return gr.update(visible=True),gr.update(visible=True),gr.update(visible=True)
def activate_full_builder_and_load_data(email):
#batting_score,chase,submit
if len(str(email))<5:
gr.Warning("Please Enter Valid Email")
return gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=True),gr.update(visible=True)
request_params = {"email":email,"flag":os.environ.get("FLAG")}
url = os.environ["FLASK_API_ACCESS"]
response = requests.post(url, json=request_params)
if response.json().get("acesss")==1:
batting_choices = response.json().get("teams")
print(batting_choices,"response from flask")
return gr.update(choices=batting_choices,visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=False),gr.update(visible=False)
else:
gr.Warning("Please Enter Registered Email")
return gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=True),gr.update(visible=True)
team_name_and_team_comp_dict={}
def display_generated_teams_df(df):
# Create a pivot table counting the number of players by team and team_id
pivot_df = pd.pivot_table(df, index='team_id', columns='team', aggfunc='size', fill_value=0)
# Reset index to make 'team_id' a column again and ensure a consistent DataFrame structure
pivot_df = pivot_df.reset_index()
# Renaming the columns if needed, for instance, to map internal team names to display names
# This can be skipped or adjusted based on your specific naming requirements
# Example: pivot_df.columns = ['Team No', 'PKBS', 'RCB']
# Adjust 'team_id' column name to 'Team No'
pivot_df.rename(columns={'team_id': 'Team No'}, inplace=True)
pivot_df["sorter"]=pivot_df['Team No'].apply(lambda x: eval(x.lower().replace("team","").strip()))
pivot_df = pivot_df.sort_values(["sorter"])
pivot_df.drop(["sorter"],inplace=True,axis=1)
return pivot_df
def sort_dataframe_by_role(df):
"""
Sorts the DataFrame by the 'Role' column according to a custom order.
Parameters:
- df: The DataFrame to be sorted.
- role_order: A list specifying the order in which roles should be sorted.
Returns:
- A DataFrame sorted by the 'Role' column according to the specified order.
"""
role_order=["Wicket-keeper", "Batsman", "All-rounder", "Bowler"]
df['Role'] = pd.Categorical(df['Role'], categories=role_order, ordered=True)
sorted_df = df.sort_values('Role')
return sorted_df
def get_teams_data(batting_team,batting_score,chase,email=""):
# print(batting_team,"bat team",batting_score,"nan score",chase)
if batting_team and batting_score and chase and len(batting_team)>0 and len(batting_score)>0 and len(chase)>0:
batting_score=batting_score.split("(")[0].strip()
if "Not" in chase:
chase = 'Collapse'
req_params = {'batting_team':batting_team,
'batting_score':batting_score,
'chase':chase,
'flag':os.environ.get("FLAG"),
"email":email}
url = os.environ["FLASK_TEAM_BUILDER"]
gr.Warning("Making Teams")
response = requests.post(url, json=req_params)
full_data = response.json()
full_data=full_data['teams_generated']
team_name_and_team_comp_dict={}
all_teams_df =[]
for idx,team in enumerate(full_data):
team_name_and_team_comp_dict[f"Team {idx+1}"]=team
team = pd.DataFrame(team)
team = team.drop_duplicates(["player_code"],ignore_index=True)
team["team_id"]=f"Team {idx+1}"
team["hit"]=team["hit"].apply(lambda x: round(float(x),1))
all_teams_df.append(team)
all_teams_df = pd.concat(all_teams_df)
display_teams_df = display_generated_teams_df(all_teams_df)
all_team_name = list(team_name_and_team_comp_dict.keys())
first_df = pd.DataFrame(team_name_and_team_comp_dict[all_team_name[0]])
first_df=first_df[["player_name","role_type","team","hit"]]
first_df.columns = ["Player Name","Role","Team","HIT%"]
first_df = sort_dataframe_by_role(first_df)
first_html = first_df.to_html(classes='ui celled table', index=False)
return gr.update(choices=all_team_name,value=all_team_name[0],visible=True,interactive=True),gr.update(value=first_html,visible=True),gr.update(visible=True),gr.update(visible=True),all_teams_df,gr.update(value=display_teams_df,visible=True)
else:
gr.Warning("Please Verify Inputs")
# return gr.update(visible=False,interactive=True),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),pd.DataFrame()
return None
def pivot_role_team_with_team_names(df):
# Copying the original dataframe to not alter it
df_copy = df.copy()
# Defining the order for the role_type
role_order = ["Wicket-keeper", "Batsman", "All-rounder", "Bowler"]
# Pivoting the dataframe
pivot_df = df_copy.pivot_table(index='role_type', columns='team', aggfunc='size', fill_value=0)
# Reindex the pivot table to ensure the order of role_types
pivot_df = pivot_df.reindex(role_order)
# Adding a total row
pivot_df.loc['Total', :] = pivot_df.sum()
# Resetting index to make 'role_type' a column instead of an index and renaming it for clarity
pivot_df.reset_index(inplace=True)
pivot_df.rename(columns={'role_type': 'Role'}, inplace=True)
pivot_df.rename_axis(None, axis=1, inplace=True)
return pivot_df
def fix_hit(hit):
try:
hit = float(hit)
hit = round(hit,1)
except Exception as e:
hit = ""
return hit
def display_selected_df(team_index,all_teams_df):
temp_df = all_teams_df[all_teams_df["team_id"]==team_index]
temp_df = temp_df.drop(["team_id","player_code"],axis=1)
temp_df2 = temp_df[["player_name","role_type","team","hit"]]
temp_df = temp_df[["player_name","role_type","team"]]
disp_df = pivot_role_team_with_team_names(temp_df)
temp_df2["hit"]=temp_df2["hit"].apply(fix_hit)
temp_df2.columns=["Player Name","Role","Team","HIT%"]
# html_header = f"<h2>{team_index}</h2>"
temp_df2 = sort_dataframe_by_role(temp_df2)
req_html= temp_df2.to_html(classes='ui celled table', index=False)
print("changing data")
return req_html,disp_df
intro_html='''<h3> Welcome to AI-Saathi </h3>
<p>Saare fantasy problems ka solution</p>
'''
intro_2_html = '''
<div style="display: flex; justify-content: center;" width="100%">
<!-- ↓ The original div -->
<div>
<h3> Welcome to AI-Saathi </h3>
<p>Saare fantasy problems ka solution</p>
</div>
</div>'''
scores = ["Low","Average","High"]
chase_vals = ["Easy Chase","Close","Collapse"]
def rs_change(rs):
if "Low" in rs:
updated_choices = ["Easy Chase","Close"]
elif "Average" in rs:
updated_choices = ["Easy Chase","Close","Not Chase"]
else:
updated_choices = ["Close","Not Chase"]
return gr.update(choices=updated_choices, value=None)
with gr.Blocks(theme=gr.themes.Default(primary_hue="amber", secondary_hue="pink")) as demo:
# gr.HTML(intro_2_html)
# logo = Image.open("assets/IMG_0453.jpg")
# gr.Image(logo)
with gr.Row():
email_input = gr.Textbox(label="Email ID",placeholder="Enter Gmail ID for Access",type='email',lines=1)
with gr.Row():
activation_btn=gr.Button("Load Team Data")
with gr.Row():
batting_team = gr.Radio(choices=[], label="Which team will bat 1st? / कौन सी टीम पहले बल्लेबाजी करेगी?",visible=False,interactive=True)
batting_score = gr.Radio(choices=["Low (1st innings < 160)", "Average (1st innings 160-195)", "High (1st innings >195)"],label="What will be 1st innings score? / पहली पारी का स्कोर क्या होगा?",visible=False,interactive=True)
chase = gr.Radio(choices=[], label="What will be 2nd inning senario?/दूसरी पारी का परिदृश्य क्या होगा?",visible=False,interactive=True)
all_teams_df = gr.DataFrame(visible=False)
with gr.Row():
submit = gr.Button("Submit",visible=False)
with gr.Row():
teams_info_disp=gr.DataFrame(visible=False,height=300)
with gr.Row():
team_dropdown = gr.Dropdown(label="Select Team",allow_custom_value=False,multiselect=False,visible=False)
with gr.Row():
html_data = gr.HTML(visible=False)
with gr.Row():
basic_status = gr.DataFrame(label="Team Stats",visible=False)
with gr.Row():
btn = gr.Button("Team improvement with AI-Saathi",visible=False)
curr_team_data=gr.DataFrame(visible=False,interactive=False)
with gr.Row():
chat_bot = gr.Chatbot(visible=False)
thread_id = gr.Textbox(value="THIS IS THE THREAD-ID",visible=False)
with gr.Row():
user_msg = gr.Textbox(placeholder="Team ko change ya improve karne ke liye suggestion le",visible=False)
with gr.Row():
clear_btn = gr.ClearButton(chat_bot,visible=False)
activation_btn.click(fn=activate_full_builder_and_load_data,inputs=[email_input,],outputs=[batting_team,batting_score,chase,submit,email_input,activation_btn])
batting_score.change(fn=rs_change, inputs=[batting_score], outputs=[chase])
submit.click(fn=get_teams_data,inputs=[batting_team,batting_score,chase,email_input],outputs=[team_dropdown,html_data,basic_status,btn,all_teams_df,teams_info_disp])
team_dropdown.change(fn=display_selected_df, inputs=[team_dropdown,all_teams_df], outputs=[html_data,basic_status])
# html_data.change(fn=put_df2use,inputs=html_data,outputs=curr_team_data)
btn.click(fn=activate_chat,inputs=[chat_bot,user_msg,clear_btn],outputs=[chat_bot,user_msg,clear_btn])
user_msg.submit(user, [user_msg, chat_bot], [user_msg, chat_bot], queue=True).then(
bot, [chat_bot,team_dropdown,all_teams_df,batting_team,batting_score,chase], chat_bot)
clear_btn.click(lambda: None, None, chat_bot, queue=False)
team_dropdown.change(lambda: None, None,chat_bot)
team_dropdown.change(lambda: None, None,thread_id)
chat_bot.like(fn=save_like_data)
demo.queue(default_concurrency_limit=3)
demo.launch(share=False)
|