Skip to content

Commit 40c9507

Browse files
author
Mael Fabien
committed
Refactor the individual features
1 parent 853a3c3 commit 40c9507

18 files changed

+527
-212
lines changed

CV_face.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import streamlit as st
2+
import matplotlib.pyplot as plt
3+
import cv2
4+
5+
def add_face():
6+
7+
st.title("Face Detection")
8+
st.write("Face detection is a central algorithm in computer vision. The algorithm implemented below is a Haar Cascade Classifier. It detects several faces using classical methods, and not deep learning. There are however important parameters to choose.")
9+
10+
font = cv2.FONT_HERSHEY_SIMPLEX
11+
cascPath = "facedetect/haarcascade_frontalface_default.xml"
12+
faceCascade = cv2.CascadeClassifier(cascPath)
13+
gray = cv2.imread('images/Women.jpg', 0)
14+
15+
st.markdown("*Original image:*")
16+
plt.figure(figsize=(12,8))
17+
plt.imshow(gray, cmap='gray')
18+
st.pyplot()
19+
20+
scaleFactor = st.sidebar.slider("Scale Factor", 1.02, 1.15, 1.1, 0.01)
21+
minNeighbors = st.sidebar.slider("Number of neighbors", 1, 15, 5, 1)
22+
minSize = st.sidebar.slider("Minimum size", 10, 200, 20, 1)
23+
24+
# Detect faces
25+
faces = faceCascade.detectMultiScale(
26+
gray,
27+
scaleFactor=scaleFactor,
28+
minNeighbors=minNeighbors,
29+
flags=cv2.CASCADE_SCALE_IMAGE
30+
)
31+
32+
# For each face
33+
for (x, y, w, h) in faces:
34+
# Draw rectangle around the face
35+
if w > minSize:
36+
cv2.rectangle(gray, (x, y), (x+w, y+h), (0, 0, 0), 5)
37+
st.markdown("*Detected faces:*")
38+
plt.figure(figsize=(12,8))
39+
plt.imshow(gray, cmap='gray')
40+
st.pyplot()

CV_yolo.py

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import streamlit as st
2+
import matplotlib.pyplot as plt
3+
import cv2
4+
import numpy as np
5+
import pandas as pd
6+
7+
def add_yolo():
8+
9+
st.title("Object Detection")
10+
st.write("Object Detection is a field which consists in identifying objects in an image or a video feed. This task involves convolutional neural networks (CNNs), a special type of deep learning architecture. The algorithm presented below is YOLO (You Only Look Once), a state-of-the-art algorithm trained to identify thousands of object types.")
11+
# This sidebar UI lets the user select parameters for the YOLO object detector.
12+
def object_detector_ui():
13+
st.sidebar.markdown("# Model")
14+
confidence_threshold = st.sidebar.slider("Confidence threshold", 0.0, 1.0, 0.5, 0.01)
15+
return confidence_threshold #overlap_threshold
16+
17+
# Draws an image with boxes overlayed to indicate the presence of cars, pedestrians etc.
18+
def draw_image_with_boxes(image, boxes):
19+
LABEL_COLORS = [0, 255, 0]
20+
image_with_boxes = image.astype(np.float64)
21+
for _, (xmin, ymin, xmax, ymax) in boxes.iterrows():
22+
image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] += LABEL_COLORS
23+
image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] /= 2
24+
25+
st.image(image_with_boxes.astype(np.uint8), use_column_width=True)
26+
27+
@st.cache(show_spinner=False)
28+
def load_present_image(img):
29+
image = cv2.imread(img, cv2.IMREAD_COLOR)
30+
image = image[:, :, [2, 1, 0]] # BGR -> RGB
31+
return image
32+
33+
def yolo_v3(image, confidence_threshold=0.5, overlap_threshold=0.3):
34+
#@st.cache()allow_output_mutation=True
35+
def load_network(config_path, weights_path):
36+
net = cv2.dnn.readNetFromDarknet(config_path, weights_path)
37+
output_layer_names = net.getLayerNames()
38+
output_layer_names = [output_layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
39+
return net, output_layer_names
40+
41+
net, output_layer_names = load_network("yolov3/yolov3.cfg", "yolov3.weights")
42+
43+
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
44+
net.setInput(blob)
45+
layer_outputs = net.forward(output_layer_names)
46+
47+
boxes, confidences, class_IDs = [], [], []
48+
H, W = image.shape[:2]
49+
50+
for output in layer_outputs:
51+
for detection in output:
52+
scores = detection[5:]
53+
classID = np.argmax(scores)
54+
confidence = scores[classID]
55+
if confidence > confidence_threshold:
56+
box = detection[0:4] * np.array([W, H, W, H])
57+
centerX, centerY, width, height = box.astype("int")
58+
x, y = int(centerX - (width / 2)), int(centerY - (height / 2))
59+
boxes.append([x, y, int(width), int(height)])
60+
confidences.append(float(confidence))
61+
class_IDs.append(classID)
62+
63+
f = open("yolov3/classes.txt", "r")
64+
f = f.readlines()
65+
f = [line.rstrip('\n') for line in list(f)]
66+
67+
try:
68+
st.subheader("Detected objects: " + ', '.join(list(set([f[obj] for obj in class_IDs]))))
69+
except IndexError:
70+
st.write("Nothing detected")
71+
72+
indices = cv2.dnn.NMSBoxes(boxes, confidences, confidence_threshold, overlap_threshold)
73+
74+
xmin, xmax, ymin, ymax, labels = [], [], [], [], []
75+
if len(indices) > 0:
76+
77+
for i in indices.flatten():
78+
79+
x, y, w, h = boxes[i][0], boxes[i][1], boxes[i][2], boxes[i][3]
80+
xmin.append(x)
81+
ymin.append(y)
82+
xmax.append(x+w)
83+
ymax.append(y+h)
84+
85+
boxes = pd.DataFrame({"xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax})
86+
return boxes[["xmin", "ymin", "xmax", "ymax"]]
87+
88+
confidence_threshold = object_detector_ui()
89+
img_type = st.sidebar.selectbox("Select image type?", ['Cars', 'People', 'Animals', "Meeting"])
90+
91+
if img_type == 'People':
92+
image_url = "images/Group.jpg"
93+
elif img_type == 'Cars':
94+
image_url = "images/cars.jpg"
95+
elif img_type == 'Animals':
96+
image_url = "images/animal.jpg"
97+
elif img_type == 'Meeting':
98+
image_url = "images/Men.jpg"
99+
100+
image = load_present_image(image_url)
101+
102+
# Get the boxes for the objects detected by YOLO by running the YOLO model.
103+
yolo_boxes = yolo_v3(image, confidence_threshold)
104+
draw_image_with_boxes(image, yolo_boxes)

NLP_flair.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import streamlit as st
2+
import flair
3+
global flair_sentiment
4+
import numpy as np
5+
6+
def load_flair():
7+
return flair.models.TextClassifier.load('en-sentiment')
8+
9+
def add_flair():
10+
11+
flair_sentiment = load_flair()
12+
13+
st.title("Sentiment Detection")
14+
st.write("Sentiment Detection from text is a classical problem. This is used when you try to predict the sentiment of comments on a restaurant review website for example, or when you receive customer support messages and want to classify them. This task usually involves Deep Learning algorithms such as Long Short-Term Memory (LSTMs). This algorithm relies on Flair, a library developped by Zalando (shopping site) research team.")
15+
16+
input_sent = st.text_input("Input Sentence", "Although quite poorly rated, the story was interesting and I enjoyed it.")
17+
18+
s = flair.data.Sentence(input_sent)
19+
flair_sentiment.predict(s)
20+
21+
st.write('Your sentence is ', str(s.labels[0]).split()[0].lower(), " with ", str(np.round(float(str(s.labels[0]).split()[1][1:-1]),3)*100), " % probability.")

NLP_ner.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import streamlit as st
2+
import spacy
3+
4+
def return_NER(value):
5+
nlp = spacy.load("en_core_web_sm")
6+
doc = nlp(value)
7+
return [(X.text, X.label_) for X in doc.ents]
8+
9+
def add_ner():
10+
11+
st.title("Named Entity Recognition")
12+
13+
st.write("Named Entity Recognition is the process by which we identify named entities (persons, organisations, governments, money...) using a mix of deep learning (Long Short-Term Memory networks) and probabilitstic approach (Conitional Random Fields). This requires to train an algorithm to make a difference between Apple (a fruit) and Apple (the brand) based on contextual information. This type of algorithm is generally trained on large corpuses such as Wikipedia. This algorithm relies on SpaCy, a state-of-the-art library which implements natural language processing models in English and French.")
14+
nlp = spacy.load("en_core_web_sm")
15+
16+
input_sent = st.text_input("Input Sentence", "Orange sells 1 million Apple's phones each year.")
17+
18+
for res in return_NER(input_sent):
19+
st.write(res[0], ":", res[1])

NLP_pos.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import streamlit as st
2+
import spacy
3+
4+
def return_pos(value):
5+
nlp = spacy.load("en_core_web_sm")
6+
doc = nlp(value)
7+
return [(X.text, X.pos_) for X in doc]
8+
9+
def add_pos():
10+
st.title("Part-Of-Speech Tagging")
11+
st.write("Part-Of-Speech Tagging is the process by which tag each word of a sentence with its correspondding grammatical function (determinant, noun, ajective...) using a mix of deep learning (Long Short-Term Memory networks) and probabilitstic approach (Conitional Random Fields). Just like Named Entity Recognition, this type of algorithm is generally trained on large corpuses such as Wikipedia. This algorithm relies on SpaCy, a state-of-the-art library which implements natural language processing models in English and French.")
12+
nlp = spacy.load("en_core_web_sm")
13+
14+
input_sent = st.text_input("Input Sentence", "Your input sentence goes here")
15+
16+
for res in return_pos(input_sent):
17+
st.write(res[0], ":", res[1])

NLP_qa.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import streamlit as st
2+
from allennlp import pretrained
3+
import matplotlib.pyplot as plt
4+
5+
def add_qa():
6+
7+
st.title("Question Answering")
8+
st.write("Question Answering is a state-of-the-art research topic that has been arising with the evolution of Deep Learning algorithms. You write a query regarding a long input text, the algorithm goes through the text and identifies the region of the text which is the most likely to contain the answer. The graph below displays 'attention', the process by which neural networks learn to focus on certain parts of the long text. The darker the cell, the most important the information was to identify the answer.")
9+
10+
predictor = st.cache(
11+
pretrained.bidirectional_attention_flow_seo_2017,
12+
ignore_hash=True # the Predictor is not hashable
13+
)()
14+
15+
article_choice = st.sidebar.selectbox("Article to query", ["Netflix", "Italy"])
16+
17+
if article_choice == "Netflix":
18+
passage = st.text_area("Article", """Netflix, Inc. is an American media-services provider and production company headquartered in Los Gatos, California, founded in 1997 by Reed Hastings and Marc Randolph in Scotts Valley, California. The company's primary business is its subscription-based streaming service which offers online streaming of a library of films and television programs, including those produced in-house. As of April 2019, Netflix had over 148 million paid subscriptions worldwide, including 60 million in the United States, and over 154 million subscriptions total including free trials. It is available worldwide except in mainland China (due to local restrictions), Syria, North Korea, and Crimea (due to US sanctions). The company also has offices in the Netherlands, Brazil, India, Japan, and South Korea. Netflix is a member of the Motion Picture Association (MPA).
19+
Netflix's initial business model included DVD sales and rental by mail, but Hastings abandoned the sales about a year after the company's founding to focus on the initial DVD rental business. Netflix expanded its business in 2010 with the introduction of streaming media while retaining the DVD and Blu-ray rental business. The company expanded internationally in 2010 with streaming available in Canada, followed by Latin America and the Caribbean. Netflix entered the content-production industry in 2012, debuting its first series Lilyhammer.
20+
Since 2012, Netflix has taken more of an active role as producer and distributor for both film and television series, and to that end, it offers a variety of "Netflix Original" content through its online library. By January 2016, Netflix services operated in more than 190 countries. Netflix released an estimated 126 original series and films in 2016, more than any other network or cable channel. Their efforts to produce new content, secure the rights for additional content, and diversify through 190 countries have resulted in the company racking up billions in debt: $21.9 billion as of September 2017, up from $16.8 billion from the previous year. $6.5 billion of this is long-term debt, while the remaining is in long-term obligations. In October 2018, Netflix announced it would raise another $2 billion in debt to help fund new content.
21+
""")
22+
question = st.text_input("Question", "Where are the headquarters of Netflix?")
23+
24+
elif article_choice == "Italy":
25+
passage = st.text_area("Passage", "Italy, officially the Italian Republic is a European country consisting of a peninsula delimited by the Alps and surrounded by several islands. Italy is located in south-central Europe, and it is also considered a part of western Europe. The country covers a total area of 301,340 km2 (116,350 sq mi) and shares land borders with France, Switzerland, Austria, Slovenia, and the enclaved microstates of Vatican City and San Marino. Italy has a territorial exclave in Switzerland (Campione) and a maritime exclave in the Tunisian Sea (Lampedusa). With around 60 million inhabitants, Italy is the fourth-most populous member state of the European Union. Due to its central geographic location in Southern Europe and the Mediterranean, Italy has historically been home to myriad peoples and cultures. In addition to the various ancient peoples dispersed throughout modern-day Italy, the most predominant being the Indo-European Italic peoples who gave the peninsula its name, beginning from the classical era, Phoenicians and Carthaginians founded colonies mostly in insular Italy, Greeks established settlements in the so-called Magna Graecia of Southern Italy, while Etruscans and Celts inhabited central and northern Italy respectively. An Italic tribe known as the Latins formed the Roman Kingdom in the 8th century BC, which eventually became a republic with a government of the Senate and the People. The Roman Republic initially conquered and assimilated its neighbours on the peninsula, eventually expanding and conquering parts of Europe, North Africa and Asia. By the first century BC, the Roman Empire emerged as the dominant power in the Mediterranean Basin and became a leading cultural, political and religious centre, inaugurating the Pax Romana, a period of more than 200 years during which Italy's law, technology, economy, art, and literature developed. Italy remained the homeland of the Romans and the metropole of the empire, whose legacy can also be observed in the global distribution of culture, governments, Christianity and the Latin script.")
26+
question = st.text_input("Question", "How large is Italy?")
27+
28+
result = predictor.predict(question, passage)
29+
30+
# From the result, we want "best_span", "question_tokens", and "passage_tokens"
31+
start, end = result["best_span"]
32+
33+
question_tokens = result["question_tokens"]
34+
passage_tokens = result["passage_tokens"]
35+
mds = [f"**{token}**" if start <= i <= end else token if start - 10 <= i <= end + 10 else "" for i, token in enumerate(passage_tokens)]
36+
st.markdown(" ".join(mds))
37+
38+
attention = result["passage_question_attention"]
39+
40+
plt.figure(figsize=(12,12))
41+
sns.heatmap(attention, cmap="YlGnBu")
42+
plt.autoscale(enable=True, axis='x')
43+
plt.xticks(np.arange(len(question_tokens)), labels=question_tokens)
44+
st.pyplot()

0 commit comments

Comments
 (0)