Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 19 September 2015

What emotions run through your playlist?

Hola !!

Long time. So I was upto creating this application one night , I named: "Playlist Emotions" , "What does the song says" :P , "PlayWithEmotions" and what not, each project of a failed experimentation.

Duh.

The project took way too long. Thanks to the noble idea of making and deploying it as a GWT application and then to improve upon the GUI of the app.
FYI , I tried but done neither of the things above. My Google Console developers trial account  supposedly has some issues with this app, yet to be resolved. So before the entire idea behind the app and the excitement of results it displays fades out , I thought, lemme write a blog post on the same.


So what is this all about?

The idea originated from a candid discussion with my friend on how songs influence our moods and also how our emotions affect the type of songs we listen to.

Being fascinated about knowing what kinds of songs I listen to, I thought of creating an application where I would just enter the folder location where my songs are and it would return me emotional composition of the songs I listen to.

Next stage was how to do that?

Logic is somewhat like this: When you share your music directory with me, I read the titles of all ,mp3 / .wav songs. Then the application extracts lyrics for those songs.

There exists no robust API that can give the lyrics of the song. Trouble multiplies when it is a Hindi Song, because we need to fetch the lyrics in English to do the sentiment analysis of the song.

So, indeed the program does a google search of "English Lyrics" + title of the song in your directory.
This gives me a list of links. I pick up the links resembling to either one of the following four trusted websites on lyrics , whichever is encountered first:
www.metrolyrics.com
www.lyricsfreak.com
www.hindilyrics.net (for Bollywood Songs)
www.bollymeaning.com (for Bollywood Songs)


Next step is scraping lyrics from these links. I studies the html structure of the websites and using JSoup library I finally fetched the string of my interest.

Then comes the third step of doing sentiment analysis, I did it using Synesketch .

"Synesketch analyses the emotional content of text sentences in terms of emotional types (happiness, sadness, anger, fear, disgust, and surprise), weights (how intense the emotion is), and a valence (is it positive or negative). The recognition technique is grounded on a refined keyword spotting method which employs a set of heuristic rules, a WordNet-based word lexicon, and a lexicon of emoticons and common abbreviations. Synesketch visualizes the emotions recognized in the form of real-time generative art. The art is partially based on Jared Tarbel’s algorithms and is inspired by the physics graphics of colliding particles."


And tadaa, I have the composition of emotions in songs I frequently listen too.
Mine was overall positive, with more of happy and surprise content :D If you want to try, find the app here:
https://github.com/nextLane/Playlist-Emotions

The code is open source, feel free to download and experiment. :)

This is how the raw application looks:


And when you get your results :D


The accuracy is challengable though, majorly because of two reasons:
1. Not the entire playlist is analysed, as in the trick that we applied to fetch the lyrics is usually applicable to around 70-80% songs, at times all, if you have named your songs properly in your playlist rather than random strings/numbers.

2. The Synesketch does sentiment analysis on words the song uses, we are equating the category of words with the category of songs, as in sad words corresponds to sad songs, This might not be the case always, for song also constitutes of musical beats , eh. Ok, just for clarification there is nothing like sad words, I just used it to indicate the set of words that can be categorized to a sad emotion. The details of it lie in the logic of Synesketch itself.
Detecting emotions in text is an ongoing research so high accuracy cannot be expected as of now.

So that was it, a whole night and the abstract thought of yesterday concreted into the application of today. Its fun to get your hands dirty into code this way.

See you in next post soon, with one more exciting creation/ exploration.

It would be great to hear your comments below!

Till then, keep hacking ;)

Adieu

Saturday, 14 March 2015

Diving Deep | Android

So here I am building my weather app on android studio, that would essentially fetch weather forecast for upcoming days. (covers lessons 1-3)

Check out:
https://github.com/udacity/Sunshine-Version-2

for more details on code we would be deliberating upon in this post. The post essentially doesn't deals with the whole details, it gives an idea on what kind of methods exist and their purpose and how it is all connected in an android app. Budding developers may find it a bit useful.

Since I have come a long distance till now, lets quickly sum up the way it is working as of now:






I have four main java classes till now:

1. MainActivity

2. Forecast Fragment

3. Detail Activity

4. Settings Activity

Let's peek into and see what these files are actually doing:

1. MainActivity: This extends ActionBarActivity
It has some basic overridden methods like:
(i) protected void onCreate(Bundle savedInstanceState)
It sets the content view to some layout XML using setContentView method.It sets the view to activity_main XML, it just has a framelayout component named container.

Then we have, onCreateOptionsMenu, this essentially inflates the main xml of menu. It has the xmls adding items like settings and refresh to it.

Then we also have one method named onOptionsItemSelected which deals with events related to selecting something from the menu bar. Comparisons like item.getItemId()==R.id.action_settings are done inside it.


2. ForecastFragment : One of the lengthiest.
It extends Fragment Class.
A Fragment is a piece of an application's user interface or behaviour that can be placed in an Activity.
In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own life cycle, that life cycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

What does it particularly deals with?

Well, that is the list of weather forecasts we wanna display. To populate the list we need to have data in some form. To do the entire thong, we need to have ArrayAdapter

  Then we have all the overridden methods:
(i)  public void onCreate(Bundle savedInstanceState)
This just setOptionsMenu true so as to detect the presence of Menu Bar for the app.

(ii) public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
This inflates the menu view having refresh feature.

(iii) public boolean onOptionsItemSelected(MenuItem item)
It features the utility that is what will happen when refresh is clicked.
We used Shared Preferences and corresponding preference manager to generalize the input for city in which we need to check weather.
 We also created the object of async class FetchWeatherClass to fetch weather from the API in background.

(iv) public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
It inflates the required layouts and xmls
Creates array list and adds ArrayAdapter to it.
Components of ArrayAdapter :
1. The current context (this activity)
2. The name of the layout ID.
3. The ID of the textview to populate.
4. The array list i.e. weekForecast in this case.


We use listView object to display the list of weathers fetched. This list View is attached with the ArrayAdapter. A setOnItemClick listener is also attached to it so that on clicking any list item a different screen (activity) may come up using Intent.

Syntax for Intent is worth a deep glance:
Here it goes:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String forecast = mForecastAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), DetailActivity.class)
                        .putExtra(Intent.EXTRA_TEXT, forecast);
                startActivity(intent);

            }
        });


We also have an inner class in this:
public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
 This is essentially to retrieve and parse JSON data retrieved from the API into string array.
The doInBackground method essentially helps in URL construction and http connection to the API.
onPostExecute does the required add ons/ changes to the adapter to reflect the fetched data.

3. Detail Activity:
 Quite simple class. It extends ActionBarActivity too as the main activity does and also has an inner fragment class as a placeholder
The onCreate, onCreateOptionsMenu and onOptionsItemSelected methods have the same functionality as they are in the main activity apart from the required changes related to fragment.


The inner class  DetailFragment with the significant onCreateView method holds some significance , making canges to the displayed text view in accordance with the intent object it has received.

4. Settings Activity:
This extends the PreferenceActivity   class and implements the interface: Preference.OnPreferenceChangeListener
It makes use of xml file namely pref_general.
We do addPreferencesFromResource(R.xml.pref_general);
and  bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));

The second method Attaches a listener so the summary is always updated with the preference value. Also fires the listener once, to initialize the summary (so it shows up before the value is changed.)

Third method is : public boolean onPreferenceChange(Preference preference, Object value)
For list preferences, look up the correct display value in the preference's 'entries' list (since they have separate labels/values).
For other preferences, set the summary to the value's simple string representation.


Please note corresponding changes are being done in AndroidManifest file parallely.


So, that's all for now. Hope this post proves useful in some way. I just experimented on the ways an app's actual functionality can be understood from the point of view of a beginner.
Feel free to drop suggestions below.

Have a great day!

Keep hacking till then! :)




A secret love message ~

Hmm, so the trick of putting up a catchy seasonal title worked out, we got you here! Folks, we will be talking about a really cool tech...