Queue-Tip/PLAI
0
1import gradio as gr2from sentence_transformers import SentenceTransformer, util3import openai4import os5 6os.environ["TOKENIZERS_PARALLELISM"] = "false"7 8# Initialize paths and model identifiers for easy configuration and maintenance9filename = "output_topic_details.txt" # Path to the file storing chess-specific details10retrieval_model_name = 'output/sentence-transformer-finetuned/'11 12openai.api_key = os.environ["OPENAI_API_KEY"]13 14system_message = "You are a chess chatbot specialized in providing information on chess rules, strategies, and terminology."15# Initial system message to set the behavior of the assistant16messages = [{"role": "system", "content": system_message}]17 18# Attempt to load the necessary models and provide feedback on success or failure19try:20 retrieval_model = SentenceTransformer(retrieval_model_name)21 print("Models loaded successfully.")22except Exception as e:23 print(f"Failed to load models: {e}")24 25def load_and_preprocess_text(filename):26 """27 Load and preprocess text from a file, removing empty lines and stripping whitespace.28 """29 try:30 with open(filename, 'r', encoding='utf-8') as file:31 segments = [line.strip() for line in file if line.strip()]32 print("Text loaded and preprocessed successfully.")33 return segments34 except Exception as e:35 print(f"Failed to load or preprocess text: {e}")36 return []37 38segments = load_and_preprocess_text(filename)39 40def find_relevant_segment(user_query, segments):41 """42 Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.43 This version finds the best match based on the content of the query.44 """45 try:46 # Lowercase the query for better matching47 lower_query = user_query.lower()48 49 # Encode the query and the segments50 query_embedding = retrieval_model.encode(lower_query)51 segment_embeddings = retrieval_model.encode(segments)52 53 # Compute cosine similarities between the query and the segments54 similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]55 56 # Find the index of the most similar segment57 best_idx = similarities.argmax()58 59 # Return the most relevant segment60 return segments[best_idx]61 except Exception as e:62 print(f"Error in finding relevant segment: {e}")63 return ""64 65def generate_response(user_query, relevant_segment):66 """67 Generate a response emphasizing the bot's capability in providing chess information.68 """69 try:70 user_message = f"Here's the information on chess: {relevant_segment}"71 72 # Append user's message to messages list73 messages.append({"role": "user", "content": user_message})74 75 response = openai.ChatCompletion.create(76 model="gpt-3.5-turbo",77 messages=messages,78 max_tokens=150,79 temperature=0.2,80 top_p=1,81 frequency_penalty=0,82 presence_penalty=083 )84 85 # Extract the response text86 output_text = response['choices'][0]['message']['content'].strip()87 88 # Append assistant's message to messages list for context89 messages.append({"role": "assistant", "content": output_text})90 91 return output_text92 93 except Exception as e:94 print(f"Error in generating response: {e}")95 return f"Error in generating response: {e}"96 97def query_model(question):98 """99 Process a question, find relevant information, and generate a response.100 """101 if question == "":102 return "Welcome to ChessBot! Ask me anything about chess rules, strategies, and terminology."103 relevant_segment = find_relevant_segment(question, segments)104 if not relevant_segment:105 return "Could not find specific information. Please refine your question."106 response = generate_response(question, relevant_segment)107 return response108 109# Define the welcome message and specific topics the chatbot can provide information about110welcome_message = """111# ♟️ Welcome to ChessBot!112 113## Your AI-driven assistant for all chess-related queries. Created by SCHOLAR1, SCHOLAR2, and SCHOLAR3 of the 2024 Kode With Klossy CITY Camp. 114"""115 116topics = """117### Feel Free to ask me anything from the topics below!118- Chess piece movements119- Special moves120- Game phases121- Common strategies122- Chess terminology123- Famous games124- Chess tactics125"""126 127# Setup the Gradio Blocks interface with custom layout components128with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:129 gr.Markdown(welcome_message) # Display the formatted welcome message130 with gr.Row():131 with gr.Column():132 gr.Markdown(topics) # Show the topics on the left side133 with gr.Row():134 with gr.Column():135 question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")136 answer = gr.Textbox(label="ChessBot Response", placeholder="ChessBot will respond here...", interactive=False, lines=10)137 submit_button = gr.Button("Submit")138 submit_button.click(fn=query_model, inputs=question, outputs=answer)139 140 141# Launch the Gradio app to allow user interaction142demo.launch(share=True)143 