Thing which seemed very Thingish inside you is quite different when it gets out into the open and has other people looking at it

Thursday, September 22, 2011

Extracting Web information using WSO2 Data Services

This blog explain how to scrape web data using wso2 data services web harvesting feature. In this tutorial I am going to extract Top rated books from Top Rated Books - Book Movement web page along with their authors and expose those data as a data service.

Before I begin lets look at how scraping works.

When you scrape a web page you need to identify the html/xml pattern. If we look at Top Rated Books - Book Movement page you can see list of books are listed along with their details. Now if we look at the page source we can see several html tags are repeated in the same manner.


If you look at it closely you can see a wrapper element which is

<div class=”rgLayoutCenter”>

and inside that wrapper element you have some thing like this.

<div class="rgLayoutTitle">First They Killed My Father: A Daughter of Cambodia Remembers (P.S.)</div>  

<div class="rgLayoutAuthor">by Loung Ung</div>

Now our basic requirement is to extract all the books along with their authors. To do that we need to find the pattern of the book title as wel as the author.

<div class="rgLayoutTitle">First They Killed My Father: A Daughter of Cambodia Remembers (P.S.)</div>  

<div class="rgLayoutAuthor">by Loung Ung</div>

we can easily write an xslt template to extract these information

<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/">

<BookInfo>

<xsl:for-each select="//div[@class='rgLayoutCenter']">

<Book>

<Title><xsl:value-of select="div[@class='rgLayoutTitle']"/></Title>

<Author><xsl:value-of select="div[@class='rgLayoutAuthor']"/></Author>

</Book>

</xsl:for-each>

</BookInfo>

</xsl:template>

</xsl:stylesheet>

Above xslt template describe to go inside each

<div class=”rgLayoutCenter”> 
element and extract value of
<div class="rgLayoutTitle">
and
<div class="rgLayoutAuthor">
and assign it to the XML elements Title and Author inside the wrapper Book element.

Creating the web harvest data service

Now we learnt the basic concepts on web scraping/web harvesting, we will straight away create the data services using WSO2 Data services server.

To install WSO2 data services download and unzip the zip file and go to $DS_HOME/bin and start up the server from the command prompt, run bin/wso2server.bat{sh}


When the server startup is complete, access http://localhost:9443/carbon in your browser. Sign in to the server using the default credentials (username=admin, password=admin) in the right hand side corner. It will redirect you to the management console page.

To create the data service click on create in the left hand side menu under Web Services -> Add -> Create

Once you click on it you will have to fill the data service information as shown below. Lets name our data service as WebHarvestDS.


Once you click on next you will be redirected to create data-source page click on add new datasource to add our web datasource.

For the web datasource you need to have a configuration file along with the web scraping url, the scraperVariable and the HTTP method to extract data.

Also we need to provide our template.xslt file location we wrote earlier.

<?xml version="1.0" encoding="UTF-8"?>

<config>

<var-def name='bookInfo'>

<xslt>

<xml>

<html-to-xml>

<http method='get' url='http://www.bookmovement.com/app/readingguide/memberRecommendations.php'/>

</html-to-xml>

</xml>

<stylesheet>

<file path="/media/ntfs/web/template.xsl"/>

</stylesheet>

</xslt>

</var-def>

</config>

Place the above configuration file inside the inline configuration section (or you can save the above configuration in your local machine and give it as a web harvest config file path)

Lets give our scraper variable as bookInfo and HTTP method as get and also our template location.


Creating the Query

Click on next to add a query. Give a queryId, scraper variable as webQuery and bookInfo.

To populate the data properly we need to give the group by element and row-name. This is to tell the web service how our result format should be. We also need to give output mapping to arrange our extracted data.

Query information.

  • QueryId – webQuery
  • Data Source – web
  • Scraper Variable-bookInfo
  • Grouped by element – Books
  • Row name – Book

output mappings

  • Element – Title
  • Element – Author


Click on Next to add operation and select the query name and give a name to our operation.


Click on finish to finish creating the data service. Go to webservices list and you can see our webservice is successfully deployed.



You can invoke the service using the try-it tool.


You can also invoke the data service using a rest call by simply typing http://localhost:9763/services/WebScraping/getBooks/ on ur browser.

Saturday, September 17, 2011

Kick start on WSO2 Stratoslive


Since we are going to see lots and lots of WSO2 Stratos related demonstrations and tutorials and powerful capabilities of cloud computing and stratos, its very important to know how to get started in WSO2 Stratos .

Getting started easy!!! all you need to do is create a StratosLive account (which is TOTALY FREE) and you can start using wso2 stratos live services right away.

Lets see how we can create a stratoslive account.
First go to the stratoslive homepage.
   

To create a new account click on “Get Started Now for Free! ” . It will redirect to a page where you need to give your Domain Information, Usage plan Information, and Contact Details.


To created a domain (a user account/ tenant) you need to give a unique tenant domuain. You can test
the uniqueness of your domain by clicking “check availability” button.
Once you give your domain name you need to select the usage plan for your domain ... there are four types of usage plans you can click on pricing details to get ll be allocated for you. For exploring StratosLive features and understanding the power of cloud computing you can select the demo version (Which is the free version).
After that you need to give your contact details for the registration purposes. Give your personal information along with your tenant-admin user name password and the verification code.
Once everything is filled properly submit the document and you will be redirected to a success page.


To activate your tenant/domain you will get a email with infomation on how you can activate your account. Once you activate you can login to your account simply by giving the username@tenantdomain and the tenant admin password you gave while registering your tenant.

When you login it will redirect to Stratos Manager home page which has all the links to StratosLive services.

To get more information regarding these services click on help it will give a brief description about each service.



To try out services by clicking on each service and have fun with cloud computing!!


Friday, September 2, 2011

Expose your databases as a service in two steps!!!



WSO2-Data Services Server provides the feature to expose your data as a service right away!!!. All you need to give is your database information and then generate data services to expose your database tables/schemas as per your need.

If you are using wso2 products for the first time ...

You need to download wso2 dataservices server.
Start up the server -> go to DS_HOME/bin/wso2server.bat | wso2server.sh (DS_HOME is where your set up is located)
Once the server is up and running open a web browser and navigate to https://localhost:9443/carbon.
Login it the server using the default credentials (username=admin, password=admin).

Also note that you need to provide the related jdbc driver for the database and put in repository/component/lib in order for this feature to work.

Step 1 :- Create a data source

In order to expose your database you need to create a data source using wso2 data services server.
To create data source click on Configure -> Data Sources



Click on add data source and give your data base information.


Once you create your data source you can test your connection by giving a validation query (ie Select 1) to make sure your connection is successful.

Step 2 Generating data services

You can start by clicking on the generate link in the main menue. Once you click on generate you will be directed to a wizard which will ask for the datasource and the database name which will be needed to expose.

Once you create you give your database name you will get the list of schemas/tables to select for your data service.




Once you select the tables of your choice then you need to decide wether you need a single service for each table or multiple services per table.

Click on next to view the created data services
Click on finish to view the deployed services.
You can try your service by clicking on try this sample for database transactions :) You can also generate axis2 clients by clicking on the data service.
Try your service








Wednesday, January 26, 2011

ChordATune and HMM (Interactive AI Systems)



Hidden Markov Model is an AI System and also a statistical probabilistic model in which the state of the process is described by a single discrete random variable. HMMs can model to determine hidden parameters from the observable data. In HMM if the current state only depends on the previous state it is known as a first
order Hidden Markov model .
ChordATune can be modeled as a first order Hidden Markov Model, the observable data can be modeled as melody notes (pitch classes) and hidden parameters which are also known as hidden states can be modeled as chords. HMM determine the hidden state sequence (Chords) when the observable sequence is given. In western music theory we know a chord progression solemnly depends on its previous chord therefore, this system can be modeled as a first order Hidden Markov Model.


Definition: A variant of a finite state machine having a set of states , Q, an observation (output), O, transition probabilities, A, Observation probabilities, B, and initial state probabilities, Π. The current state is not observable. Instead, each state produces an output with a certain probability (B). Usually the states, Q, and outputs, O, are understood, so an HMM is said to be a triple, (A, B, Π)
Elements of HMM
  • Q – States
  • O – Observation
  • A – the state-transition probability matrix
  • B – Observation probability distribution Matrix:
  • p - Initial state distribution probability
  • λ – the entire model
Following elements are further elaborated and mapped according to ChordATune system as described below.


Hidden States –Hidden states are the chords which can be applied for a given melody. ChordATune system is designed to use only for 24 types of chords due to the scalability and the complexity (12 Major chords and 12 Minor chords) therefore, this HMM has 24 possible hidden states.
Transition Probability Matrix (A) - This holds the probabilities of possible transition from one state to another. Therefore, probability of transferring from one chord to another chord is calculated by analyzing the training data.
Observations – Observations are the set of pitch classes which belongs to a given Chord. Since melody notes can have many combinations defining set of static observations can be a complex scenario and it cannot be defined statically. Therefore, a matrix called pitch class chroma vector is used to manipulate the observations. Pitch chroma vector matrix is 12X24 (12 pitch classes and 24 states-because of the 24 chord selection) is a pitch histogram for 24 chords and probability of occurring notes per a given chord. This is calculated by calculating the probabilistic occurrence of pitch notes along with its beat for a static duration. Then mapping it with the related chord so the notes which related to each chord and there beats can be calculated by the chroma vector matrix. The observations and the observation matrix are calculated by calculating the degree of relevance between pitch chroma vector and the input melody so that observations for each hidden states can be defined. The algorithms which are used to calculate this chroma vector and the calculation of observation probability matrix.
Initial state distribution is the initial probability of occurrence for a single state at a time. This can be modeled as the probability of occurring the initial chords (start chord). This can be calculated by analyzing the training data and calculating the initial probability of each chord.
Transition probability matrix holds the probabilities of transferring one chord to another. In order to incorporate the emotional factor to the system two different transition probability matrices are maintained: Major Transition Probability matrix for happy songs and Minor Transition Probability matrix for sad songs. According to the emotional factor of the given input melody, a combination of these transition matrixes is taken as shown in the following calculation.
Aij = P (Chordi /Chordi-1)

Aij = αAmajij X (1-α)Aminij
α – Emotional Factor
A – Transition Probability Matrix

Observation probability Matrix is populated using the input melody and the pitch class probability matrix. The pitch class probability matrix is a 12X24 matrix which has the probabilities of occurrence of each pitch classes for a given chord.
Bij= P (MelodyBar / Chord) Dij

(D – Pitch Class Vector)

Initial state distribution probability is the initial probability of occurrence for a single state at a time. Data driven and heuristic driven approaches are followed in order to train the model. Initial state distribution probability matrix and major minor clustering for Transition probabilities are trained using the heuristic driven approach. Transition probability matrix and pitch class probability matrix are trained using the data driven approaches. Around 250 lead sheets are used to train the ChordATune system, each of these lead sheets have monophonic melodies associated with relevant chord progression. Once the melody is processed and HMM properties are initialized according to the given melody and the emotional factor, chord progression is generated using the Viterbi algorithm.

Tuesday, January 25, 2011

Wednesday, November 24, 2010

Create Your Own Music Using ChordATune

ChordATune is a music making software where users can create their own creative music and mabe use them to create birthday cards, home made videos, play it using your guitar .. and many more. ChordATune also allows you to harmonize a known song and find their accompaniments.
In this section I will give you a step by step guide on how you can create music using ChordATune .

1. Creating a song.

There are several ways to create melodies in ChordATune.
  1. Using an existing midi file (if you have an already exsisting melody and don't know how to get the base chords) ..
  2. Using a manuscript Editor - ChordATune provides a well known tools to create manuscript notations (if you know your music theory)
  3. Using a virtual Piano.
I will explain how you can create your own melodies using the virtual piano provided by ChordATune

In the main frame of ChordATune, under creation mode select piano from the drop down list and click on create a song.

Then you will get a virtual piano as shown below ..


Here you can click on the key board and create your melody once you create the melody you can click on play to listen to your creation. If you don't like the sound of it you can click on edit and delete the unnecessary notes. If you don't like the entire melody you can click on clear and start over. To view your melody in a manuscript notation click on view. Once you are done click on save to save your creation. :)



2. Generating the harmony

Now that you have a melody you need to generate the harmony (base chords) to accompany you melody. In order to harmonize you need to follow the following steps
  1. Select the time signature (in simple terms its the beat of your melody)
  2. Input the midi file (the melody you just created) - you can listen to the melody once u input the melody
  3. Giving the emotional factor (harmony depends on user emotions therefore its important to specify what kind of song you want ie a happy song, sad song ect (if you don't like a particular harmony generated by ChordATune you can always change the emotional factor and get a complete different harmony.
  4. Generate Harmony

3 . Display Harmony

Once you generate the harmony there are several options to display the harmony.

  1. Selecting the genre - You can select the genre(style) of your choice while displaying the harmony. There are several styles allowed in ChordATune. (ie Rhumba, Swing, Disco, Rock, March)
  2. Selecting the drum beat - According to the genre users can select different drum beats)
  3. Changing the tempo - if you want to change your tempo of your song you can change the tempo using this functionality
  4. Display the harmony


Now you know how to create a simple song using ChordATune. It is advice to give different variations and experiment with your creation by choosing different emotional factors/ changing the genre/drum beat and tempo to get the best result of your choice. This way you can add your own creativity to your song.


ChordATune also allows you to generate the guitar tabs (fingering positions of guitar chords) for you melody for the guitar players :) by selecting the display style as guitar.



ChordATune also allows you to print your music as sheet music by clicking display printable version.


Now you can go to your piano/guiatar and play your music !!!

Tuesday, August 3, 2010

How to create a MYSQL data service using WSO2 data services Server

In this post I am going to explain how to create a simple data service to expose data as a service using WSO2 Data service Server..

Before we begin since I am going to create a data service for MYSQL data store you need to install and have mysql server(this can be any database server) .

Lets create a database call MyDSDB and create a table call Person.

Create database MyDSDB;
use MyDSDB;
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

show tables;

Now that we created a database and a table lets see how we can create a data service to insert and retrieve data from this table.


If you are using wso2 products for the first time ...
You need to download wso2 dataservices server.
Start up the server -> go to DS_HOME/bin/wso2server.bat | wso2server.sh (DS_HOME is where your set up is located)
Once the server is up and running open a web browser and navigate to https://localhost:9443/carbon.
Login it the server using the default credentials (username=admin, password=admin).

Also note that you need to provide the related jdbc driver for the database and put in repository/component/lib in order for this feature to work.

Step 1- Create a Data source.

Go to left hand side menu and click on Webservice -> Add -> Data Service -> Create and give a suitable service name for your data service.

Data Service Name* - MyFirstDSS



Click on Next to create the Datasource. 
Inorder to create the data service you need to specify your database information. That is done under create Data source. WSO2 data services support many types of data sources such as RDBMS,Excel,CSV,RDF etc. Here we are creating a data service for RDBMS->MYSQL therefore, lets select RDBMS as the Data Source Type and MYSQL as Database Engine.

DataSource Id - MyDS
Data Source Type - RDBMS
Database Engine - MYSQL 
Driver Class - com.mysql.jdbc.Driver
JDBC URL - jdbc:mysql://localhost:3306/MyDSDB
User Name - root
Password - password


Click test connection to test your connection.

Step 2 - Create Query.

In data services creating query doesnt mean just giving the SQL query needed for the data service. It also means defining the input parameters, and response (output parameters) and how we should get the results of our data service.

Lets first create a query to insertPersons.  In insert Person query you only give set of input parameters to input the data into the table.      
Click on Add new Query to create a new Query.

Query ID - InsertPersonQ
Data Source - MyDS
SQL - INSERT INTO Persons (P_Id, LastName, FirstName, Address,City) VALUES(?,?,?,?,?)

Click on Add input mappings to add input parameters to the query. Here we have to map each input parameter to the Mapping name along with their data type as shown below. When you are going to give input parameters you can also validate the input by adding a validator to your input such as (long,double,date and also custom validators). Please refer Adding Custom validators in oder to see how you can add custom validators.


Once you add the input parameters go to main configurations and your query will look like shown below. 

Click on save to save thequery. Now we have written a query to insert data.
Lets see how we can create a query to retrieve data.

 Add new Query -> 
Query ID - SelectPersonsQ
Data Source - MyDS
SQL - Select  P_Id, LastName, FirstName, Address,City From Persons 

Since we are getting a results (Select Query returns set of rows from our table) we need to define the result set in the data service. There are two options to add result set to your Query. You can manually go and click on add New Output Mappings and add the results (before you add you need to give the RowName and Grouped by elements ). Or you can simply create Generate response link data service server will auto generate your response for you.



Once you create the query add save and go to operation section.

Step 3 - Creating Operations

Creation operations is easy, once you create a query you need to create an operation mapping to the Queries you just created.
Click on add new operations, and it will display an operation wizard. Give an operation Name and map that operation to the queries you created.



Operation Name - GetPeople
Query ID - SelectPersonsQ


Operation Name - InsertPerson
Query ID - InsertPersonQ


Once you have added the two queries click on finish to save the data service. It will deploy the created data service as an axis2 service. If you go to Web services list you can see your newly created data service as shown below.


If you click on the data service you can see list of Quality of service operations given for that data service. You can add throttling security and catching for that data service. And also you can view the dbs (XML) of the created service by clicking on Data Service XML Editor.



<data name="MyFirstDSS">


  <config id="MyDS">
     <property name="org.wso2.ws.dataservice.driver">com.mysql.jdbc.Driver</property>
     <property name="org.wso2.ws.dataservice.protocol">jdbc:mysql://localhost:3306/MyDSDB</property>
     <property name="org.wso2.ws.dataservice.user">root</property>
     <property name="org.wso2.ws.dataservice.password">root</property>
  </config>
  <query id="InsertPersonQ" useConfig="MyDS">
     <sql>INSERT INTO Persons(P_Id, LastName, FirstName, Address,City) VALUES(?,?,?,?,?)</sql>
     <param name="P_Id" sqlType="STRING" ordinal="1" />
     <param name="LastName" sqlType="STRING" ordinal="2" />
     <param name="FirstName" sqlType="STRING" ordinal="3" />
     <param name="Address" sqlType="STRING" ordinal="4" />
     <param name="City" sqlType="STRING" ordinal="5" />
  </query>
  <query id="SelectPersonsQ" useConfig="MyDS">
     <sql>Select  P_Id, LastName, FirstName, Address,City From Persons</sql>
     <result element="Keys" rowName="Key">
        <element name="P_Id" column="P_Id" />
        <element name="LastName" column="LastName" />
        <element name="FirstName" column="FirstName" />
        <element name="Address" column="Address" />
        <element name="City" column="City" />
     </result>
  </query>
  <operation name="GetPeople">
     <call-query href="SelectPersonsQ" />
  </operation>
  <operation name="InsertPerson">
     <call-query href="InsertPersonQ">
        <with-param name="P_Id" query-param="P_Id" />
        <with-param name="LastName" query-param="LastName" />
        <with-param name="FirstName" query-param="FirstName" />
        <with-param name="Address" query-param="Address" />
        <with-param name="City" query-param="City" />
     </call-query>
  </operation>
</data>


You can invoke your service by the try-it feature by clicking on the try it link in the service dashboard.






Monday, July 26, 2010

Music Technology & ChordATune

The aim of the ChordATune system is to give a clear understanding of harmonization to novice pianists, and to create accompaniments that are musically correct. Since there can be more than one accompaniment for a given melody, ChordATune allows variations of accompaniments according to the emotional factor of the composer and the genre of music.


ChordATune has the functionality of creating new melodies using a manuscript notation or using a virtual piano, and also to browse melodies in MIDI format to be inserted into the system as input. The ability to set the emotional factor to any level of happiness or sadness lets the user generate different types of harmonies to the same melody based on different emotions ranging from happy to sad. Furthermore users can change the harmony by changing the genre, drum beat and its tempo. Once the harmony is generated it can be displayed in different genres and styles according to the manuscript notation. Furthermore, ChordATune possesses the capability to provide guitar chords in fret sheets for a given melody; this helps novice guitarists to learn chords and fingerings for new melodies. Once the accompaniments are generated they can be played as audio files. The generated accompaniments can be saved as MIDI files or manuscript notation.

ChordATune better explained according to Kolb’s (Ref) experiential learning theory model.

ChordATune, An e-learning tool for kids (and their grown-ups) ....

ChordATune is a cool interesting tool introduced to ease the task of harmonization for novice piano players and song writers. However, it further provides functionalities to learn western music theories and concepts and also gives users a chance to experiment music.


Kolb’s (Ref) experiential learning theory model that is based on a four-stage learning cycle as: Concrete Experience (CE), Reflective Observation (RO), Abstract Conceptualization (AC) and Active Experimentation (AE), and the four type definition of learning styles: Diverging (CE/RO), Assimilating (AC/RO), Converging (AC/AE) and Accommodating (CE/AE) have been considered when developing the learning tool ChordATune. Further, cognitive constructivism emphasizes two key principles for teaching and learning: namely that learning is an interactive process, and that learning should be whole, authentic and real was taken into consideration to facilitate the best solution for learners. One of the main aims of this project is to make learning harmonization an interactive process where the learner is presented with the tool to experience varieties of harmonization for the same melody through changing the emotional factor, key and time signature. The direct experience of changing the harmonization and the ability to check out a variety of solutions allows better learning; it is made interactive and entertaining rather than an isolated learning activity.

These theories also assists educators to understand that meaning is constructed as learners interact in meaningful ways with the world around them. In concatenating this factor with the ChordATune proposed solution, the isolated skill and drill process through exercises are converted to a learner interactive process where the learner is engaged in meaningful activities in setting required parameters for the harmonization process. It also allows the learner to be authentic in the activity that makes the process interesting and meaningful, making the end result learner centered and encouraging.


One of the main goals of this research is to involve the user with the emotional factor when creating harmony, thereby letting the user experiment with different styles and varieties of chord progression when displaying the harmonized melody. This helps novice pianists to develop their creativity in song writing and music creation.

Learning FunctionalitiesCEAEACRO
Creating Songs
Virtual Piano XXX
Manuscript Editor XX
Generating Harmony
Major/Minor Clustering
(Effect of emotions)
XX
Effect of genre XX
Effect of tempoXX
Effect of drum beatsXX
Use of manuscript notationXX
Use of guitar tabular formatXX

Another goal of this project is for music learners to understand the notational format of music writing. ChordATune provides a virtual piano enabling the users to create their melodies using a piano, and it provides the manuscript notation for that newly created melody. Furthermore, ChordATune demonstrates how chord progressions are arranged and how it can be displayed in guitar tabular format enabling music learners to concentrate on music theoretically as well as practically.


Saturday, June 12, 2010

Why Harmonization ? - Importance of harmonizing a melody


One of the biggest problem in song writing or piano playing (o creating your own music) is the problem of harmonization. In this blog I discuss why harmonization is crucial (getting the right chords to the right notes) and how we can overcome this problem using and interactive tool called ChordATune.

Power of harmonization
Play Melody
Play Harmonized Melody


Music is made out of melody and harmony. Melody is the basic tune of a song (which we can easily hum o we can just guess the notes using a keyboard). Harmony on the other hand is the accompaniments to a melody (base chords, drumbeats ect) which makes your song complete. Harmonization is a crucial part in song writing o piano playing because only by harmonization you can make your melody rich and power and also add emotions and color to your song. However, many people face the problem of harmonizing because you need extensive knowledge in music, years of training and practice and also some musicality in you to harmonize a song accurately.

This is where the ChordATune comes in handy... ChordATune is a powerful harmonization tool. Not only just harmonization, you can also create your own melodies the way you want (using a virtual piano or manuscript editor) and make it complete by harmonization. ChordATune let user have variety of harmonies according users emotions and styles and also provide drum beats to make your song have a rocking beat!!.ChordATune output the harmonize melody in manuscript and midi formats. ChordATune also provides a feature of guitar players where they can get guitar chords in guitar tabular format for an any given tune.

Now you can create your own music the way you want and also ChordATune provides a mechanism to save your creations in MIDI format so that you can use ur music for many other activities in your digital life.