victoriaono commited on
Commit
c50ab4f
·
verified ·
1 Parent(s): 5ea7756

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -141
app.py CHANGED
@@ -1,143 +1,34 @@
1
  import gradio as gr
2
- from sentence_transformers import SentenceTransformer, util
3
- import openai
4
- import os
5
 
6
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
7
-
8
- # Initialize paths and model identifiers for easy configuration and maintenance
9
- filename = "output_topic_details.txt" # Path to the file storing chess-specific details
10
- retrieval_model_name = 'output/sentence-transformer-finetuned/'
11
-
12
- openai.api_key = os.environ["OPENAI_API_KEY"]
13
-
14
- system_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 assistant
16
- messages = [{"role": "system", "content": system_message}]
17
-
18
- # Attempt to load the necessary models and provide feedback on success or failure
19
- try:
20
- retrieval_model = SentenceTransformer(retrieval_model_name)
21
- print("Models loaded successfully.")
22
- except Exception as e:
23
- print(f"Failed to load models: {e}")
24
-
25
- def 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 segments
34
- except Exception as e:
35
- print(f"Failed to load or preprocess text: {e}")
36
- return []
37
-
38
- segments = load_and_preprocess_text(filename)
39
-
40
- def 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 matching
47
- lower_query = user_query.lower()
48
-
49
- # Encode the query and the segments
50
- query_embedding = retrieval_model.encode(lower_query)
51
- segment_embeddings = retrieval_model.encode(segments)
52
-
53
- # Compute cosine similarities between the query and the segments
54
- similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
55
-
56
- # Find the index of the most similar segment
57
- best_idx = similarities.argmax()
58
-
59
- # Return the most relevant segment
60
- return segments[best_idx]
61
- except Exception as e:
62
- print(f"Error in finding relevant segment: {e}")
63
- return ""
64
-
65
- def generate_response(user_query, relevant_segment):
66
- """
67
- Generate a response emphasizing the bot's capability in providing chess information.
68
- """
69
- try:
70
-
71
- user_message = f"Here's the information on chess: {relevant_segment}"
72
-
73
- # Append user's message to messages list
74
- messages.append({"role": "user", "content": user_message})
75
-
76
- response = openai.ChatCompletion.create(
77
- model="gpt-3.5-turbo",
78
- messages=messages,
79
- max_tokens=150,
80
- temperature=0.2,
81
- top_p=1,
82
- frequency_penalty=0,
83
- presence_penalty=0
84
- )
85
-
86
- # Extract the response text
87
- output_text = response['choices'][0]['message']['content'].strip()
88
-
89
- # Append assistant's message to messages list for context
90
- messages.append({"role": "assistant", "content": output_text})
91
-
92
- return output_text
93
-
94
- except Exception as e:
95
- print(f"Error in generating response: {e}")
96
- return f"Error in generating response: {e}"
97
-
98
- def query_model(question):
99
- """
100
- Process a question, find relevant information, and generate a response.
101
- """
102
- if question == "":
103
- return "Welcome to ChessBot! Ask me anything about chess rules, strategies, and terminology."
104
- relevant_segment = find_relevant_segment(question, segments)
105
- if not relevant_segment:
106
- return "Could not find specific information. Please refine your question."
107
- response = generate_response(question, relevant_segment)
108
- return response
109
-
110
- # Define the welcome message and specific topics the chatbot can provide information about
111
- welcome_message = """
112
- # ♟️ Welcome to ChessBot!
113
-
114
- ## Your AI-driven assistant for all chess-related queries. Created by SCHOLAR1, SCHOLAR2, and SCHOLAR3 of the 2024 Kode With Klossy CITY Camp.
115
- """
116
-
117
- topics = """
118
- ### Feel Free to ask me anything from the topics below!
119
- - Chess piece movements
120
- - Special moves
121
- - Game phases
122
- - Common strategies
123
- - Chess terminology
124
- - Famous games
125
- - Chess tactics
126
- """
127
-
128
- # Setup the Gradio Blocks interface with custom layout components
129
- with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:
130
- gr.Markdown(welcome_message) # Display the formatted welcome message
131
- with gr.Row():
132
- with gr.Column():
133
- gr.Markdown(topics) # Show the topics on the left side
134
- with gr.Row():
135
- with gr.Column():
136
- question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")
137
- answer = gr.Textbox(label="ChessBot Response", placeholder="ChessBot will respond here...", interactive=False, lines=10)
138
- submit_button = gr.Button("Submit")
139
- submit_button.click(fn=query_model, inputs=question, outputs=answer)
140
-
141
-
142
- # Launch the Gradio app to allow user interaction
143
- demo.launch(share=True)
 
1
  import gradio as gr
 
 
 
2
 
3
+ def yes_man(message, history):
4
+ if message.endswith("?"):
5
+ return "Yes"
6
+ else:
7
+ return "Ask me anything!"
8
+
9
+ gr.ChatInterface(
10
+ yes_man,
11
+ chatbot=gr.Chatbot(height=300),
12
+ textbox=gr.Textbox(placeholder="Ask me a yes or no question", container=False, scale=7),
13
+ title="Yes Man",
14
+ description="Ask Yes Man any question",
15
+ theme="soft",
16
+ examples=["Hello", "Am I cool?", "Are tomatoes vegetables?"],
17
+ cache_examples=True,
18
+ retry_btn=None,
19
+ undo_btn="Delete Previous",
20
+ clear_btn="Clear",
21
+ ).launch()
22
+
23
+ # def load():
24
+ # return [
25
+ # ("Here's an audio", gr.Audio("https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav")),
26
+ # ("Here's an video", gr.Video("https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"))
27
+ # ]
28
+
29
+ # with gr.Blocks() as demo:
30
+ # chatbot = gr.Chatbot()
31
+ # button = gr.Button("Load audio and video")
32
+ # button.click(load, None, chatbot)
33
+
34
+ # demo.launch()