0% found this document useful (0 votes)
53 views12 pages

Ai Lab 02

Uploaded by

doodhjaleybi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views12 pages

Ai Lab 02

Uploaded by

doodhjaleybi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Bahria University

Karachi Campus

LAB EXPERIMENT NO.


_02_
LIST OF TASKS
TASK NO OBJECTIVE
1 Develop a Python application to generate data visualizations Scenario
2 Implement a text summarization model using Transformers Scenario
3 Convert images to sketches using OpenCV Scenario
4 Build a web scraper using Beautiful Soup Scenario
5 Automate WhatsApp messaging using PyWhatKit Scenario
6 Develop a text-to-speech application using pyttsx3 Scenario:

Submitted On:
Date: 26/02/2024

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


Task No. 01: Develop a Python application to generate data visualizations
Scenario: You are a data analyst working with a large dataset containing
various types of data. Your task is to create a Python application that uses the
Pandas, Matplotlib, and Seaborn libraries to perform exploratory data
analysis and generate interactive visualizations. The application should allow
users to load their dataset, explore the data, and create suitable charts and
plots for visual analysis.

Solution:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

def load_dataset(file_path):
# Load dataset
try:
df = pd.read_csv(file_path)
return df
except FileNotFoundError:
print("File not found. Please make sure the file path is correct.")

def explore_data(df):
# Display basic information about the dataset
print("Dataset Info:")
print(df.info())

# Display descriptive statistics


print("\nDescriptive Statistics:")
print(df.describe())

def create_visualizations(df):
# Create interactive visualizations
print("\nGenerating Visualizations...")

# Example visualization - Pairplot


sns.pairplot(df)
plt.title('Pairplot of the Dataset')
plt.show()

# Example visualization - Correlation Heatmap


plt.figure(figsize=(10, 8))
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.title('Correlation Heatmap')
plt.show()

def main():
# Load dataset
file_path = 'Train.csv' # Assuming 'Train.csv' is in the same directory

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


df = load_dataset(file_path)

if df is not None:
# Explore the data
explore_data(df)

# Create visualizations
create_visualizations(df)

if __name__ == "__main__":
main()

Output:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]
Task No. 02: Implement a text summarization model using Transformers
Scenario: As a natural language processing (NLP) researcher, you have been
tasked with developing a text summarization model that can generate concise
summaries of long text documents. Your task is to utilize the Transformers
library in Python to build and train a summarization model. The model
should be able to take a long text document as input and generate a concise
summary that captures the key information and main ideas.

Solution:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


Task No. 03: Convert images to sketches using OpenCV Scenario: You are a
computer vision enthusiast working on a project to develop a photo editing
application. Your task is to create a Python script that uses the OpenCV
library to convert regular images into sketches. The script should allow users
to select an image file, apply appropriate filters and transformations to
convert it into a sketch-like image, and save the resulting image to disk.

Solution:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]
Task No. 04: Build a web scraper using Beautiful Soup Scenario: You are a
data engineer working for an e-commerce company. Your task is to develop a
Python script that uses the Beautiful Soup library to scrape product
information from competitor websites. The script should be able to extract
data such as product names, descriptions, prices, and images from the target
websites and store the data in a structured format (e.g., CSV or JSON) for
further analysis.

Solution:
import requests
from bs4 import BeautifulSoup
import csv
import json
def scrape_video_info(url):
# Send a GET request to the URL
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the HTML content using Beautiful Soup
soup = BeautifulSoup(response.content, 'html.parser')
# Extract video information
video_title = soup.find('h1', class_='title style-scope ytd-video-primary-info-
renderer').text.strip()
video_description = soup.find('div', id='description').text.strip()
video_views = soup.find('span', class_='view-count style-scope yt-view-count-
renderer').text.strip()
video_likes = soup.find('yt-formatted-string', id='text', class_='style-scope ytd-
toggle-button-renderer style-text').text.strip()
video_dislikes = soup.find_all('yt-formatted-string', id='text', class_='style-scope
ytd-toggle-button-renderer')[1].text.strip()
return {
'title': video_title,
'description': video_description,
'views': video_views,
'likes': video_likes,
'dislikes': video_dislikes
}
else:
print("Failed to retrieve page:", response.status_code)
return None
def save_to_csv(video_info_list, file_path):
with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['title', 'description', 'views', 'likes', 'dislikes']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for video_info in video_info_list:
writer.writerow(video_info)
def save_to_json(video_info_list, file_path):
with open(file_path, 'w', encoding='utf-8') as jsonfile:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


json.dump(video_info_list, jsonfile, ensure_ascii=False, indent=4)
def main():
# URL of the YouTube video page to scrape
url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' # Example video URL
# Scrape video information
video_info = scrape_video_info(url)
if video_info:
# Print the scraped video information
print("Video Title:", video_info['title'])
print("Video Description:", video_info['description'])
print("Video Views:", video_info['views'])
print("Video Likes:", video_info['likes'])
print("Video Dislikes:", video_info['dislikes'])
# Save video information to CSV
save_to_csv([video_info], 'videos.csv')
# Save video information to JSON
save_to_json([video_info], 'videos.json')
if __name__ == "__main__":
main()

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


Task No. 05: Automate WhatsApp messaging using PyWhatKit Scenario: You
are a software developer working on a project to automate communication for
a small business. Your task is to create a Python script that uses the
PyWhatKit library to automate the sending of messages and images through
WhatsApp. The script should allow users to schedule the sending of messages
or images to one or more contacts at specific times or intervals.

Solution:
import pywhatkit as kit
import datetime
# Function to send a text message
def send_text_message(phone_number, message, time):
kit.sendwhatmsg(phone_number, message, time.hour, time.minute)
# Function to send an image
def send_image(phone_number, image_path, time):
kit.sendwhats_image(phone_number, image_path, time.hour, time.minute)
def main():
# Phone numbers
sender_number = "+923350039418"
receiver_number = "+923332082149"
# Menu for selecting the type of content to send
print("What would you like to send?")
print("1. Text Message")
print("2. Image")
choice = input("Enter your choice (1 or 2): ")
# Content based on user choice
if choice == "1":
# Message to be sent
message = input("Enter the message to send: ")
# Time to send the message
send_time = datetime.datetime.now() + datetime.timedelta(minutes=1) # Sending after 1
minute
# Sending text message
send_text_message(receiver_number, message, send_time)
elif choice == "2":
# Image path (if sending an image)
image_path = input("Enter the path of the image to send: ")
# Time to send the message
send_time = datetime.datetime.now() + datetime.timedelta(minutes=1) # Sending after 1
minute
# Sending image
send_image(receiver_number, image_path, send_time)
else:
print("Invalid choice. Please enter either 1 or 2.")
if __name__ == "__main__":
main()

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


Task No. 06: Develop a text-to-speech application using pyttsx3 Scenario: You
are a developer working on an accessibility project to help visually impaired
users interact with digital content. Your task is to create a Python application
that uses the pyttsx3 library to convert text into spoken words. The
application should allow users to input text, select voice settings (e.g.,
language, gender, rate), and generate audio output that can be played or
saved to a file.
Solution:
import pyttsx3

def speak_text(text, language='en', gender='female', rate=200):


# Initialize the text-to-speech engine
engine = pyttsx3.init()

# Set properties (optional)


engine.setProperty('rate', rate) # Speed of speech
voices = engine.getProperty('voices')

# Select voice based on language and gender


selected_voice = None
for voice in voices:
# Check if the voice has languages available

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]


if voice.languages:
# Check language and gender
if language.lower() in voice.languages[0].lower() and gender.lower() in
voice.name.lower():
selected_voice = voice.id
engine.setProperty('voice', selected_voice)
break
else:
print("Warning: No languages available for voice:", voice.name)

# If selected voice is not found, use default voice


if selected_voice is None:
print("Selected voice not found. Using default voice.")

# Convert text to speech


engine.say(text)

# Run the speech engine


engine.runAndWait()

def main():
# Input text from the user
text = input("Enter the text you want to convert to speech: ")

# Select language
language = input("Enter the language (e.g., en for English): ")

# Select gender
gender = input("Enter the gender of the voice (male/female): ")

# Select speech rate (words per minute)


rate = int(input("Enter the speech rate (words per minute): "))

# Convert text to speech


speak_text(text, language, gender, rate)

if __name__ == "__main__":
main()

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 02]

You might also like