Jacob McClanahan
Created December 16, 2016

WikiMe - The power of Alexa with the knowledge of WIkipedia

WikiMe couples the power of Alexa with Wikipedia. Listen and learn as Alexa instantly retrieves content via the control of your voice.

167
WikiMe  - The power of Alexa with the knowledge of WIkipedia

Things used in this project

Hardware components

Amazon Tap
Amazon Alexa Amazon Tap
Any Alexa enabled device will work
×1
Amazon Echo
Amazon Alexa Amazon Echo
×1
Echo Dot
Amazon Alexa Echo Dot
×1

Software apps and online services

AWS Lambda
Amazon Web Services AWS Lambda
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit

Schematics

WikiMe - Successful Wikipedia search

WikiMe - Vague Wikipedia search

WikiMe - Failed Wikipedia search

Code

WikiMe - Intent Schema

JSON
The schema of user intents in JSON format.
{
  "intents": [
    {
      "intent": "WikiMeIntent",
      "slots": [
     {
       "name": "Subject",
       "type": "SUBJECTS"
     }
   ]
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    }
  ]
}

WikiMe - Custom Slot

Plain text
Titled SUBJECTS as used in the intent schema. This could be any list of things you wanted to search on. The more you feed Alexa the better the AI will correctly identify the users request. I utilized the top 1,000 Wikipedia searches for 2016.
apple
cars
tesla
butter
felt
jeff bezos
steve jobs
AMGTV
10 Cloverfield Lane
104th Grey Cup
1972 Andes flight disaster
2016 Africa Women Cup of Nations
2016 Copa Sudamericana
2016 Copa Sudamericana Finals
2016 Formula One season
2016 in film
2016 Mnet Asian Music Awards
2016 United States presidential election recount and audit
2017 College Football Playoff National Championship
2017 Formula One season
21 Savage
A Tribe Called Quest
Aamir Khan
Aaron Rodgers
Abraham Lincoln
Adam Levine
Adam Thomas
Adele
Administrative share
Adolf Hitler
Adriana Lima
Advent
Advent calendar
Ae Dil Hai Mushkil
Agents of S.H.I.E.L.D. (season 4)
Akshay Kumar
Alan Rickman
Alan Ruschel
Alan Turing
Alanna Masterson
Albert Einstein
Alejandro Martinuccio
Aleppo offensive (November 2016)
Alexander Hamilton
Alexander the Great
Alexis Bledel
Alfred Nobel
Alia Bhatt
Alicia Keys
Alicia Vikander
Alien: Covenant
Alison Sudol
Allied (film)
Alt-right
Amanda Holden
Amanda Seyfried
Amazon.com
American Civil War
American Horror Story
American Horror Story: Roanoke
Amy Adams
Ananias Eloi Castro Monteiro
Andrew Breitbart
Andrew Jackson
Andrew Sachs
Android (operating system)
Android version history
Angelina Jolie
Animal Farm
Anna Faris
Anna Kendrick
Anne, Princess Royal
Anthony Eden
Anthony Hopkins
Anton Yelchin
Antony Armstrong-Jones, 1st Earl of Snowdon
Apple Inc.
Ariana Grande
Arnold Schwarzenegger
Arrival (film)
Arrow (TV series)
Ash vs Evil Dead
Ashton Kutcher
Asperger syndrome
Assassin's Creed
Assassin's Creed (film)
Assassination attempts on Fidel Castro
Atomic bombings of Hiroshima and Nagasaki
Attack on Pearl Harbor
Audrey Hepburn
Auli'i Cravalho
Australia
Avatar (2009 film)
Bangladesh
Bar bet
Barack Obama
Barney Miller
Barron Trump
Batman
Batman v Superman: Dawn of Justice
Battle of Mosul (2016)
Battlefield 1
Battlefield Earth (film)
Bay of Pigs Invasion
BDSM
Befikre
Bella Hadid
Ben Affleck
Ben Woodburn
Ben-Hur (2016 film)
Benedict Cumberbatch
Betsy DeVos
Bhumibol Adulyadej
Bigg Boss 10
Bill Clinton
Bill Gates
Bill Goldberg
Billy Gilman
Bing Crosby
Bitcoin
Blac Chyna
Black Friday (shopping)
Black Mirror
Blake Lively
Blue & Lonesome (The Rolling Stones album)
Bob Dylan
Bob Marley
Bollywood
Bonobo
Brad Pitt
Bradley Cooper
Brandy Norwood
Brazil
Brazil national football team
Breaking Bad
British Aerospace 146
Britney Spears
Brittany Murphy
Brock Lesnar
Bruce Lee
Bruno Mars
Bruno Rangel
BTS (band)
Burj Khalifa
Buzz Aldrin
Cabinet of Donald Trump
Caitlyn Jenner
Calculator
California
Call of Duty: Infinite Warfare
Canada
Candace Cameron Bure
Capgemini
Captain America: Civil War
Cara Delevingne
Carol Vorderman
Carrie Fisher
Casey Affleck
Casey Neistat
Cassandra Peterson
Catherine, Duchess of Cambridge
Chandra Nandni
Chandragupta Maurya
Channel S
Charles Dickens
Charles Manson
Charles, Prince of Wales
Charlie Chaplin
Charlize Theron
Che Guevara
Chelsea F.C.
Chernobyl disaster
Cheryl (entertainer)
Chesley Sullenberger
China
Chinese remainder theorem
Chris Hemsworth
Chris Pratt
Chrissy Teigen
Christian Slater
Christmas
Christopher Columbus
Christopher Lee
Claire Foy
Clean Bandit
Clint Eastwood
Cold War
Colin Farrell
Colin Kaepernick
Collateral Beauty
College Football Playoff
Colombia
Colonel Abrams
Colonel Sanders
Commodus
Communism
Conor McGregor
Copa Sudamericana
Counter-insurgency
Crescograph
Cristiano Ronaldo
Crowded House
Cuba
Cuban Missile Crisis
Cuban Revolution
Cyber Monday
Dab (dance)
Daisy Ridley
Dak Prescott
Dakota Access Pipeline
Dakota Access Pipeline protests
Dangal (film)
Daniel Radcliffe
Danny DeVito
Danny Mac
Danny Masterson
Darren Sharper
Darth Vader
David Attenborough
David Blaine
David Bowie
David Miscavige
David Packouz
David Petraeus
Deadpool (film)
Dear Zindagi
Death and state funeral of Fidel Castro
Death Stranding
Deaths in 2016
Deepika Padukone
Demi Moore
Derek Carr
Designated Survivor (TV series)
Desmond Doss
Dhanush
Diana, Princess of Wales
Dileep (actor)
DJ Khaled
Doctor Strange
Doctor Strange (film)
Dolly Parton
Don't Breathe
Donald Glover
Donald Trump
Dr. Dre
Drake (musician)
Dubai
Dwayne Johnson
Dwight D. Eisenhower
Dyatlov Pass incident
Earth
Eazy-E
Eddie The Eagle Edwards
Eddie Redmayne
Education in Sri Lanka
Edward Herrmann
Edward Snowden
Edward VII
Edward VIII
Efraim Diveroli
Eggnog
Elaine Chao
Electoral College (United States)
Elizabeth I of England
Elizabeth II
Elizabeth Taylor
Ellen DeGeneres
Elon Musk
Elvis Presley
Emilia Clarke
Emily Ratajkowski
Eminem
Emma Morano
Emma Roberts
Emma Stone
Emma Watson
England
English language
Ernest Hemingway
Erykah Badu
European Union
Evan Rachel Wood
Ezekiel Elliott
Ezra Miller
Facebook
Fantastic Beasts and Where to Find Them
Fantastic Beasts and Where to Find Them (film)
Fascism
FC Barcelona
Felicity Jones
Fidel Castro
Fifth Harmony
Fiji Water
Filipe Machado
Final Fantasy
Final Fantasy XV
Finding Dory
First Amendment to the United States Constitution
Flag desecration
Flag Protection Act of 2005
Florence Henderson
Floyd Mayweather Jr.
Force 2
France
Frank Sinatra
Franklin D. Roosevelt
Freddie Mercury
Frederick W. Smith
French presidential election, 2017
Friends
Fucking, Austria
Fulgencio Batista
Gal Gadot
Game of Thrones
Game of Thrones (season 7)
Garth Brooks
Gatlinburg, Tennessee
Generation X
George Clooney
George H. W. Bush
George Harrison
George S. Patton
George Soros
George V
George VI
George W. Bush
George Washington
Germany
Gigi Hadid
Gilmore Girls
Gilmore Girls: A Year in the Life
Gmail
Gone with the Wind (film)
Google
Google Chrome
Google Translate
Gotham (TV series)
Grant Tinker
Great Smog of London
Grey's Anatomy
Grey's Anatomy (season 13)
Hacksaw Ridge
Hailee Steinfeld
Hamilton (musical)
Hank Williams
Hanukkah
Hardwired... to Self-Destruct
Harley Quinn
Harrison Ford
Harry Potter
Harry Potter (film series)
Harry Potter and the Cursed Child
Harry S. Truman
Hawaii
Hazel Keech
Heath Ledger
Helen Mirren
Hell or High Water (film)
Henry Burris
Henry VIII of England
Hideo Kojima
Hilarie Burton
Hillary Clinton
HIV/AIDS
Homer at the Bat
Hong Kong
House of Cards (U.S. TV series)
How to Get Away with Murder
Howard Hughes
HTTP 404
HTTPS
Human rights in Cuba
I'm a Celebrity...Get Me Out of Here!
I'm a Celebrity...Get Me Out of Here! (UK TV series)
Iceland
Illuminati
IMDb
India
Indian 500 and 1000 rupee note demonetisation
Indian rupee
Indonesia
Inferno (2016 film)
Internet
Interstellar (film)
Invasion! (Arrowverse)
IPTV
Irina Shayk
Isaac Newton
Isaiah Austin
Isla Fisher
Islamic State of Iraq and the Levant
ISM band
Israel
Italian constitutional referendum, 2016
Italy
Ivana Trump
Ivanka Trump
Ivar the Boneless
J. Cole
J. K. Rowling
Jackie Chan
Jacqueline Kennedy Onassis
Jagadish Chandra Bose
Jake Gyllenhaal
Jakson Follmann
James Arthur Ray
James Franco
James Marsden
James Mattis
Jamie Bell
Janam TV
Japan
Jared Kushner
Jared Leto
Jared Padalecki
Jason Bourne (film)
Jason Momoa
Jason Statham
Jeffrey Dahmer
Jeffrey Dean Morgan
Jennifer Aniston
Jennifer Lawrence
Jennifer Lopez
Jennifer Nettles
Jenson Button
Jesse Owens
Jessica Alba
Jesus
Jewel (singer)
Jill Stein
Jim Carrey
Jim Harbaugh
Jimi Hendrix
Jimmy Carter
Joe McKnight
Joel Dommett
John Cena
John Christie (murderer)
John F. Kennedy
John Legend
John Lennon
Johnny Cash
Johnny Depp
Jordan Banjo
Jordan Smith (musician)
Joseph Gordon-Levitt
Joseph Stalin
Josimar (footballer born 1986)
Judah P. Benjamin
Judge Rinder
Judy Garland
Julia Roberts
Julius Caesar
Justice League (film)
Justin Bieber
Justin Trudeau
Kahaani 2: Durga Rani Singh
Kaley Cuoco
Kanye West
Karen Carpenter
Karl Marx
Kate Beckinsale
Kate Mara
Katherine Johnson
Katherine Waterston
Kavya Madhavan
Keanu Reeves
Keke Rosberg
Kellyanne Conway
Kendall Jenner
Keo Woolford
Key to My Life
Killing of Harambe
Kim Kardashian
Kingsglaive: Final Fantasy XV
Kirk Douglas
Kodak Black
Krampus
Krampus (film)
Ku Klux Klan
Kubo and the Two Strings
Kylie Jenner
L. Ron Hubbard
La La Land (film)
La7
Lady Gaga
LaMia Airlines Flight 2933
LaMia Flight 2933
Larry Lamb
Lauren Graham
Leah Remini
LeBron James
Lee Harvey Oswald
Legends of Tomorrow
Leonard Cohen
Leonardo da Vinci
Leonardo DiCaprio
Lewis Hamilton
Liam Neeson
Liam Payne
Lin-Manuel Miranda
Lionel Messi
Lisa Snowdon
List of accidents involving sports teams
List of amendments to the United States Constitution
List of Arrow episodes
List of banks in India
List of Black Mirror episodes
List of Bollywood films of 2016
List of Christmas carols
List of countries by cement production
List of countries by GDP (nominal)
List of countries by past and future GDP (nominal) per capita
List of Dragon Ball Super episodes
List of Formula One World Drivers' Champions
List of Gilmore Girls characters
List of Gilmore Girls episodes
List of Gotham episodes
List of highest-grossing films
List of highest-grossing Indian films
List of Hindi film clans
List of Internet exchange points by size
List of James Bond films
List of Lucifer episodes
List of Marvel Cinematic Universe films
List of most subscribed users on YouTube
List of most viewed YouTube videos
List of Naruto: Shippuden episodes
List of pipeline accidents in the United States in the 21st cen...
List of Presidents of the United States
List of Running Man episodes
List of Shameless (U.S. TV series) episodes
List of South Park episodes
List of Steven Universe episodes
List of Super Bowl champions
List of Supergirl episodes
List of supporting Harry Potter characters
List of The Big Bang Theory episodes
List of The Flash episodes
List of The Walking Dead episodes
List of UFC events
List of United States cities by population
List of Victoria's Secret models
List of Vikings episodes
List of Walt Disney Pictures films
List of works by Vincent van Gogh
List of WWE pay-per-view events
List of WWE personnel
Little Women
Liza Weil
London
Loretta Lynn
Los Angeles
Louisa May Alcott
Louise Linton
Love Actually
Lucas Gomes da Silva
Lucifer (TV series)
Lucille Ball
Luke Hemsworth
Lyndon B. Johnson
Macaulay Culkin
Machine Gun Kelly (rapper)
Madonna (entertainer)
Mads Mikkelsen
Magnus Carlsen
Mahatma Gandhi
Mahendra Singh Dhoni
Malcolm X
Manchester by the Sea (film)
Manchester United F.C.
Mandy Moore
Mannequin Challenge
Marcelo Augusto Mathias da Silva
Marcelo Boeck
Marcos Danilo Padilha
Marfan syndrome
Margaret Rhodes
Margot Robbie
Mariah Carey
Marilyn Manson
Marilyn Monroe
Marion Cotillard
Mark Wahlberg
Mark Zuckerberg
Marla Maples
Marlon Brando
Martin Luther King Jr.
Martin Roberts (presenter)
Martin Shkreli
Marvel Cinematic Universe
Marxism
Mary of Teck
Mary Tyler Moore
Mary, Queen of Scots
Mateus Caramelo
Matheus Biteco
Matt Czuchry
Matt Damon
Matthew Broderick
Matthew McConaughey
McDonald's
Meghan Markle
Melania Trump
Melissa Benoist
Melissa McCarthy
Metallica
Mexico
Mia Khalifa
Michael Fassbender
Michael Jackson
Michael Jordan
Michael Schumacher
Michelle Obama
Mike Pence
Mila Kunis
Miley Cyrus
Millennials
Milo Ventimiglia
Milo Yiannopoulos
Mirta Diaz-Balart
Mitch McConnell
Mitt Romney
Mnet Asian Music Awards
Moana (2016 film)
Mohamed Hadid
Mona Lisa
Moonlight (2016 film)
Morena Baccarin
Muhammad
Muhammad Ali
Munich air disaster
Murder of Skylar Neese
Myanmar
Nancy Pelosi
Napoleon
Narcissistic personality disorder
Narcos
Narendra Modi
Natalie Portman
Natalie Wood
NATO phonetic alphabet
Negan
Neil Diamond
Nelson Mandela
Netherlands
Neto (footballer, born 1985)
New York City
New Zealand
Neymar
Nick Saban
Nicki Minaj
Nico Rosberg
Nicole Kidman
Nicole Scherzinger
Nikki Haley
Nikola Tesla
Nineteen Eighty-Four
Noam Chomsky
Nocturnal Animals
Nocturnal Animals (film)
Note
O. J. Simpson
Odell Beckham Jr.
Ola Jordan
Once Upon a Time (TV series)
One Direction
Ottawa Redblacks
Ottoman Empire
P. J. Fleck
Pablo Escobar
Pakistan
Park Geun-hye
Passengers (2016 film)
Patrick Stewart
Paul Nuttall
Paul Walker
Paytm
Pentatonix
Periodic table
Peter Krause
Peter Townsend (RAF officer)
Philippines
Pierre Trudeau
Planet Earth II
PlayStation 4
Pornhub
Prasar Bharati
President of the United States
Prince (musician)
Prince Andrew, Duke of York
Prince Edward, Earl of Wessex
Prince Harry
Prince Philip, Duke of Edinburgh
Prince William, Duke of Cambridge
Princess Margaret, Countess of Snowdon
Printer steganography
Priyanka Chopra
Proyecto 40
Qamar Javed Bajwa
Quantico (TV series)
Queen Elizabeth The Queen Mother
Queen Victoria
R v Dudley and Stephens
Rachel McAdams
Rae Sremmurd
Rafael Ramos de Lima
Ragnar Lodbrok
Ralph Lazo
Ranveer Singh
RB Leipzig
Real Madrid C.F.
Richard Nixon
Rihanna
Riot grrrl
Rita Ora
River Phoenix
Riverdale (2017 TV series)
RMS Titanic
Roadblock: End of the Line
Rob Gronkowski
Robert De Niro
Robin Williams
Rogue One
Ron Glass
Ronald Reagan
Ronaldinho
Rooney Mara
Rooting (Android OS)
Rosa Parks
Rothschild family
Royal Rumble (2017)
Rudolph the Red-Nosed Reindeer (TV special)
RuPay
Russia
Ryan Reynolds
Ryan Thomas
Saithan
Salman Khan
Sam Quek
Samantha Morton
Santa Claus
Santa Claus's reindeer
Sasha Banks
Saudi Arabia
Sausage Party
Saving Private Ryan
Savitar (comics)
Scarlett Johansson
Scarlett Moffatt
Scientology
Scientology and celebrities
Scott Patterson
Sean Connery
Sean Taylor
Selena Gomez
September 11 attacks
Sergey Karjakin
Seven deadly sins
Sex (book)
Sexual intercourse
Shah Rukh Khan
Shailene Woodley
Shakira
Shameless (season 7)
Shameless (U.S. TV series)
Shaquille O'Neal
Sherlock (TV series)
Shia LaBeouf
Shigeru Miyamoto
Shivaay
Shooter (TV series)
Sia Furler
Silence (2016 film)
Sing (2016 film)
Singapore
Snipe hunt
Snoop Dogg
Socrates
South Africa
South Korea
South Park (season 20)
Soviet Union
Spain
Spider-Man: Homecoming
Spite house
Srinivasa Ramanujan
St. Andrew's Day
Standard deviation
Standing Rock Indian Reservation
Star Trek Beyond
Star Wars
Star Wars: Episode VIII
Star Wars: The Force Awakens
Starboy (album)
Stephen Curry
Stephen Hawking
Steve Bannon
Steve Jobs
Steven Mnuchin
Steven Seagal
Story of Your Life
Stranger Things (TV series)
Suicide Squad (film)
Sully (film)
Sunny Leone
Super Bowl XXX
Superga air disaster
Supergirl (TV series)
Supernatural (season 12)
Supernatural (U.S. TV series)
Survivor Series (2016)
Survivor: Millennials vs. Gen X
Sutherland's Portrait of Winston Churchill
Switzerland
Sylvester Stallone
Syrian Civil War
Taiwan
Taj Mahal
Talulah Riley
Taylor Swift
Ted Bundy
Teddy Riley
Ten Commandments
Texas v. Johnson
Thailand
Thandie Newton
Thanksgiving
Thanksgiving (United States)
The 100 (TV series)
The Affair (TV series)
The Band
The Beatles
The Belko Experiment
The Big Bang Theory
The Big Bang Theory (season 10)
The Brady Bunch
The Chainsmokers
The Crown (TV series)
The Edge of Seventeen
The Elf on the Shelf
The Flash (2014 TV series)
The Grand Tour (TV series)
The Hole (Scientology)
The Holocaust
The Jungle Book (2016 film)
The Last Guardian
The Last of Us
The Legend of the Blue Sea
The Man in the High Castle (TV series)
The Missing (TV series)
The Mummy (2017 film)
The Nutcracker
The Revenant (2015 film)
The Rolling Stones
The Shack
The Simpsons
The Twelve Days of Christmas (song)
The Ultimate Fighter: Tournament of Champions
The Undertaker
The Vampire Diaries
The Vampire Diaries (season 8)
The Voice (U.S. season 11)
The Walking Dead (season 7)
The Walking Dead (TV series)
The Weeknd
The X Factor (UK series 13)
The Young Pope
Theodore Roosevelt
Thiego
This Is Us (TV series)
Thomas Edison
Thomas Jefferson
Thomas Sadoski
Tiffany Trump
Tiger Woods
Tim Elliott
Tim Tebow
Timeless (TV series)
Tina Turner
TLC: Tables, Ladders & Chairs (2016)
Tom Brady
Tom Cruise
Tom Ford
Tom Hanks
Tom Hardy
Tom Herman (American football)
Tom Price (U.S. politician)
Tomi Lahren
Tony Bellew
Trevor Noah
Trolls (film)
Tuberculosis
Tum Bin II
Tupac Shakur
Turkey
Turkey (bird)
Twenty One Pilots
Tyreek Hill
UFC 206
UFC 207
UFC Fight Night: Lewis vs. Abdurakhimov
UFC Fight Night: Whittaker vs. Brunson
Underworld (film series)
Underworld: Blood Wars
Uniform resource locator
United Arab Emirates
United Kingdom
United Nations
United States
United States presidential election, 2000
United States presidential election, 2004
United States presidential election, 2008
United States presidential election, 2012
United States presidential election, 2016
United States presidential line of succession
United States Secretary of Defense
Urjit Patel
US Airways Flight 1549
Vaani Kapoor
Vagina
Vajiralongkorn
Vasyl Lomachenko
Vietnam War
Vikings (season 4)
Vikings (TV series)
Vin Diesel
Vincent Kartheiser
Vincent van Gogh
Virat Kohli
Vladimir Putin
Wajah Tum Ho
Wallis Simpson
Walt Disney
War Dogs (2016 film)
Warren Buffett
Washington, D.C.
Watch Dogs 2
Wayne Bridge
Website
Welsh Corgi
Westworld
Westworld (TV series)
WhatsApp
White elephant gift exchange
Whitey Bulger
Wiki
Wikipedia
Wilbur Ross
Will Smith
William Shakespeare
Winnie Harlow
Winston Churchill
Wonder Woman
Wonders of the World
World Chess Championship 2016
World War I
World War II
WWE TLC: Tables, Ladders & Chairs
X-Men (film series)
X-Men: Apocalypse
XHamster
XXX
XXX: Return of Xander Cage
XXXX
Yolanda Hadid
Young M.A
Your Name
YouTube
Yuri on Ice
Yuvraj Singh
Zayn Malik
Zinedine Zidane
Zootopia

WikiMe - Sample Utterances

Plain text
These are what people say to interact with WikiMe.
WikiMeIntent search for {Subject}
WikiMeIntent look up {Subject}
WikiMeIntent tell me about {Subject}

WikiMe - AWS Lambda python code

Python
This is the AWS Lambda function that brokers the logic between Alexa skill and Wikipedia
from __future__ import print_function
import wikipedia

# ----------------------- Main handler ---------------------------

def lambda_handler(event, context):
    # Logging
    print("event.session.application.applicationId=" + event['session']['application']['applicationId'])

    # Lock Lamda from other requests
    if (event['session']['application']['applicationId'] != "amzn1.ask.skill.xxxxxxxxxxxx-xxxxxx-xxxxx-xxxxx-xxxxxxxxxxxxxx"):
        raise ValueError("Invalid Application ID, %".format(applicationId))

    if event['session']['new']: 
        on_session_started({'requestId': event['request']['requestId']}, event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])

    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])

    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])



# --------------- Functions that control the skill's behavior ------------------
def get_welcome_response():# Session started
    session_attributes = {}
    card_title = "Wiki Me"
    speech_output = "Welcome to Wiki Me. " \
                    "Please tell me what you are looking for by saying " \
                    "search for iphone or look up Nicola Tesla"

    reprompt_text = "Please tell me what you would like info on, " \
                    "like tell me about "
    should_end_session = False
    return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))


def handle_session_end_request(): # End Session
    card_title = "Session Ended"
    speech_output = "Thank you for using Wiki Me " \
                    "Have a great day! "
    should_end_session = True
    return build_response({}, build_speechlet_response(card_title, speech_output, None, should_end_session))


def create_wikime_query_attributes(wikime_query):
    return {"wikimequery": wikime_query}

#Sets the subject in the session and prepares the speech to reply to the user
def set_query_in_session(intent, session):    
    card_title = intent['slots']['Subject']['value']
    session_attributes = {}
    should_end_session = False

    if 'Subject' in intent['slots']:
        wikime_query = intent['slots']['Subject']['value']
        session_attributes = create_wikime_query_attributes(wikime_query)
        speech_output = get_query_result(wikime_query)

        reprompt_text = "You can ask me to look something up for you by saying, " \
                        "tell me about Intel."
    else:
        speech_output = "I'm not sure what you are searching for " \
                        "Please try again."
        reprompt_text = "I can help you research a topic on wikipedia" \
                        "You can ask me to look up information for you by saying, " \
                        "look up scuba diving."
    return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))



# --------------- Events ------------------

# Called when the session starts
def on_session_started(session_started_request, session):
    # Purely for backend logging
    print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId'])


def on_launch(launch_request, session):
    # Called when the user launches the skill without specifying any parms
    print("on_launch requestId=" + launch_request['requestId'] +", sessionId="+ session['sessionId'])
    # Dispatch to your skill launch function
    return get_welcome_response()


def on_intent(intent_request, session):
    # Called when the user specifies an intent for this skill
    # Logging
    print("on_intent requestId=" + intent_request['requestId'] + ", sessionId="+ session['sessionId'])

    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']
    print(intent_name)
    # Dispatch to your skill's intent handlers
    if intent_name == "WikiMeIntent":
        return set_query_in_session(intent, session)
    #elif intent_name == "WhatsMyColorIntent":
    #    return get_color_from_session(intent, session)
    elif intent_name == "AMAZON.HelpIntent":
        return get_welcome_response()
    elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
        return handle_session_end_request()
    else:
        raise ValueError("Invalid intent")


def on_session_ended(session_ended_request, session):
    # Called when the user ends the session.
    # Is not called when the skill returns should_end_session=true
    print("on_session_ended requestId=" + session_ended_request['requestId'] +", sessionId=" + session['sessionId'])
    


# --------------- Helpers that build all of the responses ----------------------

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },
        'card': {
            'type': 'Simple',
            'title': "SessionSpeechlet - " + title,
            'content': "SessionSpeechlet - " + output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }


def build_response(session_attributes, speechlet_response):
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speechlet_response
    }


# -------------Wiki Functions------------------------

def get_query_result(query):
    try:
        result = wikipedia.summary(query, sentences=3).encode('utf-8')
        print("wiki query=" + query)
        #return get_found_response(query, result)
        sanitized = remove_text_inside_brackets(result)
        return sanitized

    except wikipedia.exceptions.DisambiguationError as error:
        return get_suggested_response(error.options)

    except wikipedia.exceptions.PageError as error:
        return get_notfound_response(query)

    except wikipedia.exceptions.WikipediaException as error:
        return get_emptyquery_response()


def remove_text_inside_brackets(text, brackets="()[]"):
    count = [0] * (len(brackets) // 2) # count open/close brackets
    saved_chars = []
    for character in text:
        for i, b in enumerate(brackets):
            if character == b: # found bracket
                kind, is_close = divmod(i, 2)
                count[kind] += (-1)**is_close # `+1`: open, `-1`: close
                if count[kind] < 0: # unbalanced bracket
                    count[kind] = 0
                break
        else: # character is not a bracket
            if not any(count): # outside brackets
                saved_chars.append(character)
    return ''.join(saved_chars)

def get_page_info(query):
    fullpage =  wikipedia.page(query)
    return fullpage


def get_suggested_response(options):
    header_text = "Sorry, but you must be a little more precise try asking about {}"
    suggested_queries = get_suggested_options(options, 4)
    suggested_response = header_text.format(get_suggested_string(suggested_queries))
    return suggested_response


def get_notfound_response(query):
    preresponse = ["Well, that's awkard.  I can't find anything for", "I didn't find anything for", "Wow, I'm stumped.  Couldn't find"]
    header_text = "Well, that's awkward. I couldn't find anything for {}."
    return header_text.format(query)


def get_suggested_options(result, max_length):
    return result[:max_length]


def get_suggested_string(query):#find relavent terms if initial query was too broad
    suggested = ''
    last = query[-1]
    for element in query:
        if element == last:
            suggested += "or {}.".format(element)
        else:
            suggested += "{}, ".format(element)
    return suggested

Credits

Jacob McClanahan

Jacob McClanahan

1 project • 1 follower

Comments