frazcvchatbot / aneet11.py
amitkumar1508in's picture
Upload folder using huggingface_hub
0e47d92 verified
Raw History Blame Contribute Delete
19.3 kB
from dotenv import load_dotenv
from openai import OpenAI
import json
import os
import requests
from pypdf import PdfReader
import gradio as gr
import glob
import random
import threading
import time
import io
import pathlib
import base64
# Load environment variables from .env file
load_dotenv(override=True)
def push(text):
"""
Sends a push notification using the Pushover API.
This function requires PUSHOVER_TOKEN and PUSHOVER_USER
to be set as environment variables.
"""
requests.post(
"https://api.pushover.net/1/messages.json",
data={
"token": os.getenv("PUSHOVER_TOKEN"),
"user": os.getenv("PUSHOVER_USER"),
"message": text,
}
)
def record_user_details(email, name="Name not provided", notes="not provided"):
"""
Records a user's details and sends a push notification.
"""
push(f"Recording {name} with email {email} and notes {notes}")
return {"recorded": "ok"}
def record_unknown_question(question):
"""
Records an unanswered question and sends a push notification.
"""
push(f"Recording {question}")
return {"recorded": "ok"}
def get_instagram_link():
"""
Returns the Instagram URL for Aneet Padda.
"""
return {"url": "https://www.instagram.com/aneetpadda_/"}
def get_local_images():
"""
Selects four unique random image paths from me/images.
"""
image_paths = glob.glob('me/images/*')
if len(image_paths) < 4:
# Fallback if there are fewer than 4 images
return image_paths + [None] * (4 - len(image_paths))
return random.sample(image_paths, 4)
def browse_for_image():
"""
Fetches a list of images that are likely to be of movie actresses.
Note: A real-time web search for specific images is not possible in this environment.
This function returns a hardcoded set of working image URLs.
"""
# Using placeholder images that will always be available
return [
"https://placehold.co/600x400/FF5733/FFFFFF?text=Image+1",
"https://placehold.co/600x400/33FF57/000000?text=Image+2",
"https://placehold.co/600x400/3357FF/FFFFFF?text=Image+3",
"https://placehold.co/600x400/FF33A1/000000?text=Image+4",
"https://placehold.co/600x400/A133FF/FFFFFF?text=Image+5",
"https://placehold.co/600x400/57FF33/000000?text=Image+6",
"https://placehold.co/600x400/FF5733/FFFFFF?text=Image+7",
"https://placehold.co/600x400/33FF57/000000?text=Image+8"
]
def get_next_images(history):
"""
Selects the next four images to display. The first time, it shows images from the local
'me/images' folder. Subsequent clicks will fetch new, random images from the internet.
"""
# Check if this is the first click or if we are already displaying internet images
if not history or not all(isinstance(path, str) and path.startswith('me/images') for path in history):
# Fetch new random images from the internet
all_internet_images = browse_for_image()
new_images = random.sample(all_internet_images, 4)
history = new_images
return new_images[0], new_images[1], new_images[2], new_images[3], history
else:
# Initial display of local images
unshown_images = [path for path in get_local_images() if path not in history]
if len(unshown_images) >= 4:
selected_images = random.sample(unshown_images, 4)
history.extend(selected_images)
return selected_images[0], selected_images[1], selected_images[2], selected_images[3], history
else:
# Local images exhausted, switch to internet images
all_internet_images = browse_for_image()
new_images = random.sample(all_internet_images, 4)
history = new_images
return new_images[0], new_images[1], new_images[2], new_images[3], history
def reset_images():
"""
Resets the displayed images to the initial set from the local 'me/images' folder.
"""
initial_images = get_local_images()
return initial_images[0], initial_images[1], initial_images[2], initial_images[3], initial_images
# Tool definitions for function calling
record_user_details_json = {
"name": "record_user_details",
"description": "Use this tool to record that a user is interested in being in touch and provided an email address",
"parameters": {
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "The email address of this user"
},
"name": {
"type": "string",
"description": "The user's name, if they provided it"
},
"notes": {
"type": "string",
"description": "Any additional information about the conversation that's worth recording to give context"
}
},
"required": ["email"],
"additionalProperties": False
}
}
record_unknown_question_json = {
"name": "record_unknown_question",
"description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer",
"parameters": {
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "The question that couldn't be answered"
},
},
"required": ["question"],
"additionalProperties": False
}
}
get_instagram_link_json = {
"name": "get_instagram_link",
"description": "Always use this tool when a user asks for Aneet Padda's Instagram link",
"parameters": {
"type": "object",
"properties": {},
"additionalProperties": False
}
}
tools = [
{"type": "function", "function": record_user_details_json},
{"type": "function", "function": record_unknown_question_json},
{"type": "function", "function": get_instagram_link_json}
]
class Me:
def __init__(self):
# Initialize the Gemini client using the OpenAI library with the specified base URL and model.
# This allows using the OpenAI-compatible API endpoint for Gemini.
# Make sure to have GOOGLE_API_KEY set in your environment or .env file.
google_api_key = os.getenv("GOOGLE_API_KEY")
self.gemini = OpenAI(api_key=google_api_key, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
self.model_name = "gemini-2.0-flash"
self.name = "Aneet Padda"
# Read the LinkedIn profile from the PDF
reader = PdfReader("me/aneetinfo.pdf")
self.linkedin = ""
for page in reader.pages:
text = page.extract_text()
if text:
self.linkedin += text
# Read the summary from the text file
with open("me/summary.txt", "r", encoding="utf-8") as f:
self.summary = f.read()
# Get local images to reference in the system prompt
self.local_images = glob.glob('me/images/*')
self.image_description = "The following images of Aneet Padda are available: " + ", ".join(self.local_images)
def handle_tool_call(self, tool_calls):
"""
Executes the function calls returned by the model.
"""
results = []
for tool_call in tool_calls:
tool_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"Tool called: {tool_name}", flush=True)
tool = globals().get(tool_name)
result = tool(**arguments) if tool else {}
results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id})
return results
def system_prompt(self):
"""
Generates the system prompt for the model.
"""
system_prompt = f"You are acting as {self.name}. You are answering questions on {self.name}'s website, \
particularly questions related to {self.name}'s career, background, skills and experience. \
Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \
You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \
Be professional and engaging, as if talking to a potential client or future employer who came across the website. \
If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \
If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \
If a user asks for your social media, like your Instagram, you can use your get_instagram_link tool to provide the URL."
# Add a more casual, friendly, and expressive tone to the system prompt
system_prompt += "\n\nYour tone should be casual and friendly, like you're chatting with a friend. Feel free to use emojis and conversational language to make the interaction more engaging. \
When a user sends an image, you should act like a friend commenting on it. If it's a nice, appropriate image, give a positive comment. If it's an inappropriate or bad image, you should say 'please don't send images like this.' Make sure to summarize the image in a fun, conversational way before replying."
system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n"
system_prompt += f"## Available Images:\n{self.image_description}\n\n"
system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}."
return system_prompt
def chat(self, message, history):
"""
Handles the chat conversation with the model, including image processing.
"""
# Send a notification for every user message received.
push(f"New user question: {message}")
# Handle the user message, which may include an image
messages = [{"role": "system", "content": self.system_prompt()}] + history
# Check if the user message contains an image
if isinstance(message, tuple) and message: # This is the corrected check for image uploads from Gradio
image_path = message[0]
# Read the image and encode to base64
# Use 'rb' to read the file in binary mode for base64 encoding
with open(image_path, "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
# Create the payload for the vision model
vision_message = {
"role": "user",
"parts": [
{"text": "Describe this image and tell me if it's appropriate. Then give a short, friendly comment on it."},
{"inline_data": {"mime_type": "image/jpeg", "data": base64_image}}
]
}
# Send a notification with a summary of the image
push(f"User uploaded an image. Analyzing image content...")
# Call Gemini with the image and text prompt
try:
vision_response = self.gemini.chat.completions.create(
model=self.model_name,
messages=messages + [vision_message],
tools=tools
)
agent_reply = vision_response.choices[0].message.content
return agent_reply
except Exception as e:
print(f"Error processing image: {e}")
return "I'm sorry, I couldn't process that image right now."
else: # Regular text message
messages.append({"role": "user", "content": message})
done = False
while not done:
response = self.gemini.chat.completions.create(model=self.model_name, messages=messages, tools=tools)
if response.choices[0].finish_reason=="tool_calls":
message = response.choices[0].message
tool_calls = message.tool_calls
results = self.handle_tool_call(tool_calls)
messages.append(message)
messages.extend(results)
else:
done = True
return response.choices[0].message.content
# Function to get a random image from the local folder for the profile pic
def get_random_local_image():
image_paths = glob.glob('me/images/*')
if image_paths:
return random.choice(image_paths)
return None # Return None if no images are found
if __name__ == "__main__":
# Custom CSS for the new design
custom_css = """
body {
background-color: #000;
color: #fff;
}
.gradio-container.dark {
background-color: #000;
}
.gradio-container .main {
padding: 0;
max-width: none;
}
.chat-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
background-color: #000;
border-bottom: 1px solid #333;
}
.chat-header-img {
width: 100px;
height: 100px;
border-radius: 50%;
object-fit: cover;
border: 3px solid #666;
}
.chat-header-text h3 {
margin: 10px 0 0;
font-size: 1.5em;
text-align: center;
}
.chat-header-text p {
margin: 0;
font-size: 0.9em;
color: #bbb;
text-align: center;
}
.chat-input-row {
background-color: #000;
padding: 10px;
border-top: 1px solid #333;
display: flex;
align-items: center;
}
#msg_box {
background-color: #222;
border-radius: 20px;
border: 1px solid #444;
color: white;
padding: 10px;
}
#upload_btn {
background-color: transparent;
border: none;
color: white;
font-size: 1.5em;
padding: 5px;
cursor: pointer;
}
.gradio-container .message {
border-radius: 20px;
padding: 10px 15px;
}
.gradio-container .message-wrap.user {
background-color: #007aff;
color: white;
}
.gradio-container .message-wrap.bot {
background-color: #2c2c2c;
color: white;
}
.blue-checkmark {
color: #007aff;
}
"""
me = Me()
# Initial images to display
initial_images = get_local_images()
initial_profile_image = get_random_local_image()
with gr.Blocks(css=custom_css, theme=gr.themes.Monochrome(
font=["Inter", "sans-serif"],
primary_hue="blue",
neutral_hue="gray",
)) as demo:
# State to keep track of chat history
chatbot_state = gr.State([])
# New chat interface with a single profile header
with gr.Column(elem_id="main-chat-container"):
with gr.Row(elem_classes=["chat-header"]):
profile_button = gr.Button(
variant="link",
elem_classes=["chat-header-img-button"],
interactive=True
)
profile_image = gr.Image(
value=initial_profile_image,
show_label=False,
elem_classes=["chat-header-img"],
interactive=False # Make the image itself not interactive
)
with gr.Column(elem_classes=["chat-header-text"]):
gr.Markdown("### Aneet Padda <span class='blue-checkmark'>✅</span>")
gr.Markdown("aneetpadda_ · Instagram")
# View Profile button to redirect to Instagram
gr.Button("View Profile", link="https://www.instagram.com/aneetpadda_/")
# Chatbot and message input
chatbot = gr.Chatbot(label="Chat with the agent", type="messages", layout="bubble", height=500)
# The input area, with the upload button inside the textbox
with gr.Row(elem_classes=["chat-input-row"]):
with gr.Row(elem_id="msg_box"):
upload_btn = gr.UploadButton(
"📎",
file_types=["image"],
file_count="single",
elem_id="upload_btn"
)
msg = gr.Textbox(placeholder="Message...", show_label=False, scale=1)
submit_btn = gr.Button("➡️", scale=0, variant="primary")
# Functions to handle messages and uploads
def add_message(text, file_obj, history):
if file_obj:
history.append(((file_obj.name,), None))
elif text:
history.append([text, None])
else:
return history
return "", None, history
def get_agent_response(history):
if not history:
return history
user_message = history[-1][0]
response = me.chat(user_message, history[:-1])
history[-1][1] = response
return history
# Connect the components to their functions
msg.submit(
fn=add_message,
inputs=[msg, gr.File(visible=False), chatbot_state],
outputs=[msg, upload_btn, chatbot_state],
queue=False,
).then(
fn=get_agent_response,
inputs=chatbot_state,
outputs=chatbot,
queue=False
)
submit_btn.click(
fn=add_message,
inputs=[msg, gr.File(visible=False), chatbot_state],
outputs=[msg, upload_btn, chatbot_state],
queue=False,
).then(
fn=get_agent_response,
inputs=chatbot_state,
outputs=chatbot,
queue=False
)
upload_btn.upload(
fn=add_message,
inputs=[msg, upload_btn, chatbot_state],
outputs=[msg, upload_btn, chatbot_state],
queue=False,
).then(
fn=get_agent_response,
inputs=chatbot_state,
outputs=chatbot,
queue=False
)
# Make the profile image clickable to change the image
profile_button.click(
fn=get_random_local_image,
inputs=None,
outputs=profile_image
)
demo.launch()