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"

{team_index}

" 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='''

Welcome to AI-Saathi

Saare fantasy problems ka solution

''' intro_2_html = '''

Welcome to AI-Saathi

Saare fantasy problems ka solution

''' 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)