Skip to content

Commit 0c87b0b

Browse files
Merge pull request HarshCasper#6 from HarshCasper/master
Getting changes
2 parents f8a739d + 772f2e3 commit 0c87b0b

29 files changed

+727
-86
lines changed

Python/ASCIIfy_Image/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# ASCIIfy your image
2+
3+
This python script converts the input image to an ascii version of itself. This is achieved by giving different range of grayscale value to different special characters from the ASCII set. The whole image is then converted based on this.
4+
5+
## Setting up:
6+
7+
- Create a virtual environment and activate it
8+
9+
- Install the requirements
10+
11+
```sh
12+
$ pip install pillow
13+
```
14+
15+
## Running the script:
16+
17+
```sh
18+
$ python asciify.py [image_path] #without the brackets
19+
```
20+
21+
## Example running the script
22+
23+
```sh
24+
$ python asciify.py input.jpg
25+
```
26+
27+
![Input image](input.jpg)
28+
29+
### Will be converted to....
30+
<br>
31+
32+
![Converted image](image.png)

Python/ASCIIfy_Image/asciify.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import sys
2+
from PIL import Image, ImageDraw
3+
4+
'''
5+
A grayscale pixel value is converted into one of these special characters
6+
'''
7+
ASCII_SET = ['@','#','$','%','?','*','+',';',':',',','.']
8+
9+
'''
10+
method resize()
11+
- takes parameter image and new_width
12+
- resizes the image into new_width maintaining the aspect aspect_ratio
13+
- returns this resized image, new width and new height
14+
'''
15+
def resize(image, new_width=100):
16+
(old_width, old_height) = image.size
17+
aspect_ratio = old_height/old_width
18+
new_height = int(aspect_ratio*new_width)
19+
new_image = image.resize((new_width,new_height))
20+
return new_image, new_width, new_height
21+
22+
'''
23+
method convertToGray()
24+
- takes parameter image
25+
- returns converted grayscale image
26+
'''
27+
def convertToGray(image):
28+
return image.convert('L')
29+
30+
'''
31+
method PixelToAscii()
32+
- takes parameter image
33+
- returns a string with all image pixels converted to ascii special symbols from ASCII_SET
34+
'''
35+
def PixelToAscii(image, buckets=25):
36+
pixels = list(image.getdata())
37+
new_pixels = [ASCII_SET[pixel_value//buckets] for pixel_value in pixels]
38+
return ''.join(new_pixels)
39+
40+
'''
41+
method saveImage()
42+
- takes parameter string, new width and new height
43+
- writes the string in an image and saves the image as image.png
44+
'''
45+
def saveImage(ascii_str, new_width, new_height):
46+
image = Image.new(mode = "RGB", size = (new_width*11,new_height*11), color = "white")
47+
draw = ImageDraw.Draw(image)
48+
draw.multiline_text((0,0), ascii_str, fill=(0,0,0), align='center',spacing=0)
49+
image.save('image.png')
50+
51+
'''
52+
method asciify()
53+
- takes parameter image path
54+
- calls the required functions to asciify the image
55+
'''
56+
def asciify(img_path):
57+
try:
58+
image = Image.open(img_path)
59+
except Exception:
60+
print("Unable to find image in", img_path)
61+
return
62+
image, new_width, new_height = resize(image)
63+
gray_image = convertToGray(image)
64+
ascii_char_list = PixelToAscii(gray_image)
65+
66+
len_ascii_list = len(ascii_char_list)
67+
ascii_str = ''
68+
ascii_str = ''.join([ascii_str+i+i for i in ascii_char_list])
69+
70+
ascii_str = [ascii_str[index:index+2*new_width] for index in range(0, 2*len_ascii_list, 2*new_width)]
71+
ascii_str = "\n".join(ascii_str)
72+
73+
saveImage(ascii_str, new_width, new_height)
74+
75+
if __name__ == '__main__':
76+
if len(sys.argv)>1:
77+
img_path = str(" ".join(sys.argv[1:]))
78+
asciify(img_path)

Python/ASCIIfy_Image/image.png

59.8 KB
Loading

Python/ASCIIfy_Image/input.jpg

36.1 KB
Loading

Python/Aws/Readme.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# How do I create an S3 Bucket?
2+
3+
Before you can upload data to Amazon S3, you must create a bucket in one of the AWS Regions to store your data.
4+
After you create a bucket, you can upload an unlimited number of data objects to the bucket.
5+
6+
The AWS account that creates the bucket owns it. By default, you can create up to 100 buckets in each of your AWS accounts.
7+
If you need additional buckets, you can increase your account bucket quota to a maximum of 1,000 buckets by submitting a service quota increase.
8+
For information about how to increase your bucket quota, see AWS Service Quotas in the AWS General Reference.
9+
10+
## To create a bucket using python
11+
12+
Step 1 : Install boto3 library
13+
14+
A low-level client representing Amazon Simple Storage Service (S3):
15+
16+
Step 2 :
17+
18+
The following operations are related to CreateBucket :
19+
20+
PutObject
21+
DeleteBucket
22+
23+
See also: [Documentation](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html)
24+
25+
Examples
26+
27+
The following example creates a bucket. The request specifies an AWS region where to create the bucket.
28+
29+
`import boto3`
30+
31+
`client = boto3.client('s3')`
32+
33+
`response = client.create_bucket(
34+
Bucket='examplebucket',
35+
CreateBucketConfiguration={
36+
'LocationConstraint': 'eu-west-1',
37+
}
38+
)`

Python/Aws/createS3Bucket.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import boto3
2+
import os
3+
import datetime
4+
5+
6+
class s3Bucket:
7+
def __init__(self, bucketName: str) -> None:
8+
self.bucketName = bucketName
9+
10+
def createS3Bucket(self):
11+
try:
12+
client = boto3.client("s3")
13+
client.create_bucket(
14+
ACL="private",
15+
Bucket=self.bucketName,
16+
CreateBucketConfiguration={"LocationConstraint": "us-west-1"},
17+
)
18+
except Exception as err:
19+
print(err)
20+
else:
21+
print("S3 bucket creation Successful!")
22+
23+
24+
if __name__ == "__main__":
25+
date = datetime.datetime.now()
26+
current_time = "{}{}{}".format(date.month, date.day, date.year)
27+
bucketName = "yourName{}".format(current_time)
28+
obj = s3Bucket(bucketName)
29+
obj.createS3Bucket()

Python/Aws/moveFile.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import boto3
2+
3+
awsAccessKeyId = ""
4+
awsSecretAccessKey = ""
5+
bucketName= ""
6+
directoryName = ""
7+
s3 = boto3.resource(
8+
's3',
9+
aws_access_key_id=awsAccessKeyId,
10+
aws_secret_access_key=awsSecretAccessKey
11+
)
12+
myBucket = s3.Bucket(bucketName)
13+
14+
def moveFile():
15+
try:
16+
for objectSummary in myBucket.objects.filter(Prefix=directoryName):
17+
s3FilePath = objectSummary.key
18+
sourceFilename = (s3FilePath).split("/")[-1]
19+
copySource = {"Bucket": bucketName, "Key": s3FilePath}
20+
targetFilename = f"{destinationDirectory}/{sourceFilename}"
21+
s3.meta.client.copy(copySource, bucketName, targetFilename)
22+
s3.Object(bucketName, s3FilePath).delete()
23+
except Exception as err:
24+
print(err)
25+
26+
if __name__ == '__main__':
27+
moveFile()

Python/Aws/seceretManager.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
## AWS Secrets Manager
2+
3+
This Python example shows you how to retrieve the decrypted secret value from an AWS Secrets Manager secret. The secret could be created using either the Secrets Manager console or the CLI/SDK.
4+
5+
The code uses the AWS SDK for Python to retrieve a decrypted secret value.
6+
7+
# Prerequisite tasks
8+
9+
To set up and run this example, you must first set up the following:
10+
11+
1. Configure your AWS credentials, as described in [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html).
12+
2. Create a secret with the AWS Secrets Manager, as described in the [AWS Secrets Manager Developer Guide](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)
13+
14+
# Retrieve the secret value
15+
16+
The following example shows how to:
17+
18+
1. Retrieve a secret value using `get_secret_value`.

Python/Aws/secretManager.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import json
2+
import boto3
3+
import sys
4+
from botocore.exceptions import ClientError
5+
6+
class secretManagerClass:
7+
def __init__(self, secretName: str, regionName: str) -> None:
8+
self.secretName = secretName
9+
self.regionName = regionName
10+
11+
def getSecretFromSecretManager(self) -> json:
12+
session = boto3.session.Session()
13+
client = session.client(
14+
service_name="secretsmanager", region_name=self.regionName
15+
)
16+
try:
17+
getSecretValueResponse = client.get_secret_value(SecretId=self.secretName)
18+
19+
except ClientError as err:
20+
if err.response["Error"]["Code"] == "ResourceNotFoundException":
21+
print(f"The requested secret {self.secretName} was not found")
22+
sys.exit(err)
23+
elif err.response["Error"]["Code"] == "InvalidRequestException":
24+
print(f"The request was invalid due to: {err}")
25+
sys.exit(err)
26+
elif err.response["Error"]["Code"] == "InvalidParameterException":
27+
print(f"The request had invalid params: {err}")
28+
sys.exit(err)
29+
else:
30+
if "SecretString" in getSecretValueResponse:
31+
return json.loads(getSecretValueResponse["SecretString"])
32+
else:
33+
raise ValueError("SecretString not found in reponse")
34+
35+

Python/IMDB_scrapper/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
## IMDB Scrapper
2+
3+
This script takes a movie name as input and returns the information about that movie.
4+
5+
## Requirements for this script:
6+
7+
1. BeautifulSoup4
8+
2. requests
9+
10+
install these two by running the following command:
11+
12+
pip install -r requirements.txt
13+
14+
## How to use this script?
15+
16+
Just type the following in your command prompt:
17+
18+
python imdb_scrapper.py -l <movie_name>
19+
20+
## Sample of the script in action:
21+
22+
<p align = "center">
23+
<img src="sample.PNG" alt="movies">
24+
</p>

Python/IMDB_scrapper/imdb_scrapper.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import requests
2+
from bs4 import BeautifulSoup as bs
3+
import sys
4+
import argparse
5+
6+
# Code to add the command line interface
7+
parser = argparse.ArgumentParser()
8+
parser.add_argument("-l", "--movie", required=True, help="Movie Name")
9+
args = vars(parser.parse_args())
10+
11+
#Base IMBD URL to search for movie titles
12+
IMDB_URL = "https://www.imdb.com/search/title/?title="
13+
14+
#Movie the user wants to search for
15+
USER_DEFINED_MOVIE = args['movie']
16+
17+
#To handle connection error
18+
try:
19+
response = requests.get(IMDB_URL+USER_DEFINED_MOVIE)
20+
21+
except requests.exceptions.ConnectionError as error:
22+
sys.exit("Check your connection!")
23+
24+
#Creating a soup object
25+
soup = bs(response.content, 'html.parser')
26+
27+
#Function to scrap the details about the movie, set n/a if some detail is missing and store the detail into a dictionary
28+
def scrap_and_store(soup):
29+
30+
#This dictionary stores the movie information
31+
movie_info = {}
32+
33+
#Try and except blocks to ensure correct data retrival
34+
try:
35+
movie = soup.select(".lister-item-content")[0]
36+
except:
37+
movie = "N/A"
38+
39+
if movie == "N/A":
40+
sys.exit("Movie not found in IMDB")
41+
42+
try:
43+
movie_info['Name'] = movie.find("a").contents[0]
44+
except:
45+
movie_info['Name'] = "N/A"
46+
try:
47+
movie_info['Rating'] = movie.select(".value")[0].contents[0]
48+
except:
49+
movie_info['Rating'] = "N/A"
50+
try:
51+
movie_info['Released'] = movie.find_all("span")[1].contents[0][1:-1]
52+
except:
53+
movie_info['Released'] = "N/A"
54+
try:
55+
movie_info['Certificate'] = movie.select(".certificate")[0].contents[0]
56+
except:
57+
movie_info['Certificate'] = "N/A"
58+
try:
59+
movie_info['Runtime'] = movie.select(".runtime")[0].contents[0]
60+
except:
61+
movie_info['Runtime'] = "N/A"
62+
try:
63+
movie_info['Genre'] = movie.select(".genre")[0].contents[0].strip()
64+
except :
65+
movie_info['Genre'] = "N/A"
66+
try:
67+
movie_info['Summary'] = movie.select(".text-muted")[2].contents[0].strip()
68+
except:
69+
movie_info['Summary'] = "N/A"
70+
try:
71+
movie_info['Director'] = movie.find_all('p')[2].find_all("a")[0].contents[0]
72+
except:
73+
movie_info['Director'] = "N/A"
74+
75+
try:
76+
cast_members = movie.find_all('p')[2].find_all("a")[1:]
77+
except:
78+
cast_members = []
79+
80+
cast_name = ""
81+
for member in cast_members:
82+
cast_name+=member.contents[0]+", "
83+
84+
85+
movie_info['Cast'] = cast_name[:-2]
86+
return movie_info
87+
88+
#This function fetches the movie information and prints it systematically
89+
def main():
90+
91+
info = scrape_and_store(soup)
92+
for key,value in info.items():
93+
print(f"{key} : {value}")

Python/IMDB_scrapper/requirements.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
beautifulsoup4==4.9.1
2+
certifi==2020.6.20
3+
chardet==3.0.4
4+
idna==2.10
5+
requests==2.24.0
6+
soupsieve==2.0.1
7+
urllib3==1.25.10

Python/IMDB_scrapper/sample.PNG

96.5 KB
Loading

0 commit comments

Comments
 (0)