Python Open Ended Code
Python Open Ended Code
PY
import speech_recognition as sr
import wikipedia
import datetime
import pyjokes
import pywhatkit
import webbrowser
import requests
import random
import threading
import time
import re
from intent_detector import detect_intent
from datetime import datetime, timedelta
import pandas as pd
import random
import ast
df_pa�erns = pd.read_csv('df_pa�erns.csv')
df_responses = pd.read_csv('df_responses.csv')
delayed_messages = []
recognizer = sr.Recognizer()
def recognize_audio(file_path):
with sr.AudioFile(file_path) as source:
audio_data = recognizer.record(source)
command = recognizer.recognize_google(audio_data)
return command.lower()
if intent == "wikipedia_search":
return duckduckgo_search(command)
elif intent == "play_music":
song = command.replace("play", "").strip()
pywhatkit.playonyt(song)
return f"Playing {song} on YouTube."
else:
return "I couldn't understand the command. Please try again."
except Exception as e:
return f"Error occurred: {str(e)}"
matched_intent = None
for _, row in df_pa�erns.iterrows():
try:
pa�erns = ast.literal_eval(row['text']) # Safely parse list string
if any(pa�ern.lower() in command for pa�ern in pa�erns):
matched_intent = row['intent']
break
except Exception as e:
print("Pa�ern parsing error:", e)
if matched_intent:
response_row = df_responses[df_responses['intent'] == matched_intent]
if not response_row.empty:
try:
responses = ast.literal_eval(response_row['responses'].values[0])
return random.choice(responses)
except Exception as e:
print("Response parsing error:", e)
return "Sorry, I couldn't generate a response right now."
else:
fallback_responses = [
"That's interesting!",
"I'm here if you need anything.",
"Sounds good!",
"Let's do something fun!"
]
return random.choice(fallback_responses)
import requests
def get_news():
try:
url =
"h�ps://gnews.io/api/v4/top-headlines?lang=en&country=in&max=3&apikey=2dd3dfcd95f7dcef71a5dd9ce499d
37c"
response = requests.get(url)
data = response.json()
articles = data.get("articles", [])
if not articles:
return "No news available at the moment."
news_summary = []
for i, article in enumerate(articles):
title = article.get("title", "No title")
description = article.get("description", "No description")
source = article.get("source", {}).get("name", "Unknown Source")
forma�ed = (
f"{i+1}. {title}\n"
f" {source}\n"
f" {description}\n"
)
news_summary.append(forma�ed)
def get_fun_fact():
try:
response = requests.get("h�ps://uselessfacts.jsph.pl/random.json?language=en")
data = response.json()
return f"Here's a fun fact: {data.get('text', 'Could not fetch a fact at this moment.')}"
except Exception as e:
return f"Failed to fetch fun fact: {str(e)}"
def duckduckgo_search(query):
try:
params = {
"q": query,
"format": "json",
"no_html": 1,
"skip_disambig": 1
}
response = requests.get("h�ps://api.duckduckgo.com/", params=params)
data = response.json()
abstract = data.get("Abstract")
if abstract:
return abstract
elif data.get("RelatedTopics"):
for topic in data["RelatedTopics"]:
if "Text" in topic:
return topic["Text"]
return "I couldn't find a good answer, but you can try searching it online."
except Exception as e:
return f"Failed to fetch information: {str(e)}"
task = match.group(1)
duration = int(match.group(2))
unit = match.group(3)
def remind():
time.sleep(delay)
delayed_messages.append(f" Reminder: Don't forget to {task}!")
threading.Thread(target=remind).start()
return f"Okay, I will remind you to {task} in {duration} {unit}."
import threading
import time
from datetime import datetime, timedelta
import re
from playsound import playsound # Make sure playsound is installed: pip install playsound
def alarm():
time.sleep(seconds_until_alarm)
delayed_messages.append(" Alarm ringing! Time to wake up!")
start_time = time.time()
duration = 60 # Repeat for 1 minute
while time.time() - start_time < duration:
try:
playsound("alarm.mp3")
except Exception as e:
print(f"Error playing sound: {e}")
break
threading.Thread(target=alarm).start()
return f"Alarm set for {alarm_time.strftime('%I:%M %p')}."
def get_weather(command):
try:
# Extract city name from command using regex like "weather in Mysore"
match = re.search(r"(?:weather\s*(?:in|at)?\s*)([a-zA-Z\s]+)", command)
if match:
city = match.group(1).strip()
else:
# Try fallback: extract city using common phrases
match = re.search(r"(?:in|at)\s+([a-zA-Z\s]+)", command)
if match:
city = match.group(1).strip()
else:
return "Please specify the city name like 'weather in Chennai'."
api_key = "2f400256790f47b64cb1fdc7c8876ea7" # Replace with real key
url = f"h�ps://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
data = response.json()
if data.get("cod") != 200:
return f"Couldn't fetch weather for {city}. Please check the city name."
weather_desc = data["weather"][0]["description"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
wind = data["wind"]["speed"]
return (
f" Weather in {city.title()}:\n"
f"• Description: {weather_desc.capitalize()}\n"
f"• Temperature: {temp}°C (Feels like {feels_like}°C)\n"
f"• Humidity: {humidity}%\n"
f"• Wind Speed: {wind} m/s"
)
except Exception as e:
return f"Failed to fetch weather: {str(e)}"
INTENTS.PY
# intents.py
import pandas as pd
import ast
df = pd.read_csv('df_pa�erns.csv')
casual_talk_pa�erns = []
for item in df['text']:
try:
pa�erns = ast.literal_eval(item)
casual_talk_pa�erns.extend(pa�erns)
except:
continue
INTENTS = {
"get_time": ["what time", "current time", "tell me the time"],
"get_date": ["what date", "today's date", "current date"],
"play_music": ["play", "play song", "play music"],
"tell_joke": ["joke", "make me laugh", "tell me something funny"],
"fun_fact": ["fun fact", "interesting fact", "something cool"],
"get_news": ["news", "headlines", "latest news"],
"get_weather": ["weather", "temperature", "climate"],
"casual_talk": casual_talk_pa�erns,
"wikipedia_search": ["who is", "what is", "tell me about", "where is", "how does"],
"open_website": ["open"],
INTENT_DETECTOR.PY
def detect_intent(command):
command = command.lower()
for intent, keywords in INTENTS.items():
for keyword in keywords:
if keyword in command:
return intent
return "unknown"
MAIN.PY
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["h�p://localhost:5008"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
UPLOAD_FOLDER = "audio_files"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
@app.post("/voice-command/")
async def handle_audio(file: UploadFile = File(...)):
file_id = str(uuid.uuid4())
original_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_original.webm")
converted_path = os.path.join(UPLOAD_FOLDER, f"{file_id}.wav")
try:
# Convert to WAV
audio = AudioSegment.from_file(original_path)
audio.export(converted_path, format="wav")
# Recognize audio
command = recognize_audio(converted_path)
print(f"Recognized: {command}")
except Exception as e:
print("Error:", e)
return {"error": str(e)}
finally:
# Clean up temporary files
if os.path.exists(original_path):
os.remove(original_path)
if os.path.exists(converted_path):
os.remove(converted_path)
@app.get("/get-delayed-messages")
def get_delayed_messages():
global delayed_messages
messages = delayed_messages[:]
delayed_messages.clear()
return {"messages": messages}
CONVERSATION.PY
import numpy as np
import json
import pandas as pd
import re
import torch
import random
import torch.nn as nn
import transformers
import gc
from transformers import BertTokenizer , BertModel
import matplotlib.pyplot as plt
device = torch.device('cuda')
import torch.nn.functional as F
from torch.optim import Adam
from tqdm import tqdm
import os
class cfg:
num_classes=22
epochs=15
batch_size=10
lr=1e-5
max_length=15
df = pd.DataFrame(data['intents'])
df.head()
print(df_pa�erns)
df_pa�erns.to_csv('df_pa�erns.csv', index=False)
df_responses.to_csv('df_responses.csv', index=False)