Click here to Skip to main content
Licence GPL3
First Posted 17 Dec 2011
Views 3,036
Downloads 180
Bookmarked 6 times

cn5apinet - ConceptNet5 API Library

By | 18 Dec 2011 | Article
Connect to ConceptNet 5's REST API
(Note: cn5apinet.dll has Newtonsoft.Json.dll (Json40r5) dependency for json handling.) Download and Install yEd Graph Editor so you can display the .graphml files the demo creates. For the Demo to run, Please make certain you have Microsoft .Net 4 Runtime

Introduction

ConceptNetAPI Demo GraphML result GraphML result

ConceptNet¹ is a commonsense knowledgebase, composed mainly from the Open Mind Project, written and maintained by Massachusetts Institute of Technology (MIT). This library is something I threw together to communicate with ConceptNet 5 (beta at the time of this writing). It uses a Representational state transfer (REST) API, like ConceptNet 4, but has a different structure and design. ConceptNet 5 "is a graph; To be precise, it's a hypergraph, meaning it has edges about edges. Each statement in ConceptNet has justfications pointing to it, explaining where it comes from and how reliable the information seems to be."

The .NET C# ConceptNet API Class Library (cn5apinet)

cn5apinet can provide an interface to ConceptNet 5 REST API. Use the API to receive back Lists and objects of a ConceptNet 5 hypergraph. What is new from cnapinet (from ConceptNet4) is a new namespace for auto-creating GraphML xml files. This name space is quickly explained below. The demo displays how to assemble the cn5apinet.GraphML.GraphMLFile

cn5apinet Namespace


cn5apinet Classes
GraphML Classes

(click to make larger)


cn5apinet namespace

cn5apinetGraphMLNamespace



The Demo

[Please make certain you have Microsoft .Net 4 Runtime]

The demo app has two tabs "Test Commonsense" and "get". "Test Commonsense" tab allows you to query the ConceptNet 5 (CN5) hypergraph's knowledge and results in an answer of "Yes", "No", "Maybe"; it basically tells you if it thinks your statement is true, false, or perhaps true. This is based off the scores in the CN5 hypergraph [0 <= is false, 1 = maybe, 2 > is true]. For example, a score of 42.39 has a higher confidence score than a score of 3.87.

The second tab "get", displays more technical information and allows for some options. Download and Install yEd Graph Editor so you can display the .graphml files the demo creates. This tab was mainly based off of ConceptNet5's Web API documentation. Sometimes, screenshots are the best to explain things so please take a look below.

cn5apinet Implementation

  1. Add cn5apinet.dll to your project 'References' via Solution Explorer. (For cn5apinet.dll v1.6.x.x make sure that Newtonsoft.Json.dll (Json40r5) resides in the same folder as cn5apinet.dll) .
  2. Add 'using cn5apinet;', etc to your source code to use the namespace.
  3. Create the main API engine with 'ConceptNetAPI CNClient = new ConceptNetAPI();', etc.
  4. Below are the methods in ConceptNetAPI

ConceptNetAPI Members

Performing the lookup

//lookup_concept_raw test
cn5_node raw_concept = CNClient.lookup_concept_raw(LANG.en, tbGetPreview.Text.Trim().Split('/')[1]);
if (raw_concept != null)
{
     tbOutputGet.AppendText("lookup_concept_raw response : " + Environment.NewLine);
     tbOutputGet.AppendText(raw_concept.PPrint());
}
else
     tbOutputGet.AppendText("null");

tbOutputGet.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

Creating the .graphml

List<cn5apinet.GraphML.GraphMLNode> nodeList = new List<cn5apinet.GraphML.GraphMLNode>();
List<cn5apinet.GraphML.GraphMLEdge> edgeList = new List<cn5apinet.GraphML.GraphMLEdge>();
List<edge_arg> edge_argList = new List<edge_arg>();

#region GraphML
if (cBoxGraphML.Checked)
{
    //let's look at the edges, nodes and create a graphML

    //Create the seed node...
    GraphMLNode node0 = new GraphMLNode(0, new Geometry(30.0, 50.0, 1, 1));//customize the node...
    node0.Text = tbGetKey.Text.Trim();
    node0.FillColor = "#00FF00";//Green
    //Add this node to list
    nodeList.Add(node0);
    int i = 1;
    if ((List<Object>)raw_concept.incoming_edges != null)
    {
        foreach (object o in (List<Object>)raw_concept.incoming_edges)
        {
            string s = o.GetType().Name;
            if (o.GetType().Name == "edge_arg")
            {
                //need Json to convert o;
                Dictionary<String, String> startDict = new Dictionary<string, string>();
                String[] spiltstart = Convert.ToString(((edge_arg)o).start).Split(',');
                // [0] = "/assertion//relation/AtLocation/"
                // [1] = "/concept/en/book/"
                // [2] = "/concept/en/shelf/"

                //= Convert.ToString(((edge_arg)o).key);
                //Create the connecting Edge...
                //Add this node
                GraphMLNode nodeX = new GraphMLNode(i, new Geometry(30.0, 50.0, 1, 0));
                string[] nodetext = spiltstart[2].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                nodeX.Text = nodetext[nodetext.Length - 1];
                nodeList.Add(nodeX);
                edge_argList.Add((edge_arg)o);//add to edge_argList

                //Add this edge to list
                string[] edgetext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                GraphMLEdge edge0 = new GraphMLEdge(i, node0.NodeID, nodeX.NodeID, edgetext[edgetext.Length - 1] + " " + Convert.ToString(((edge_arg)o).score));
                edgeList.Add(edge0);
                i = i + 1;
            }
        }
    }
    //Re-arrange the nodes
    int numofNodes = nodeList.Count;
    int g = 1;
    //Draw the nodes around first node[0] in a circle
    double radius = 100.0;
    if (numofNodes > 10)
        radius = (nodeList[0].Geometry.height * 0.45) * numofNodes / 2;

    for (double h = 0.0; h < 360.0; h += (360 / numofNodes))
    {
        if (g >= numofNodes)
            break;
        double angle = h * System.Math.PI / 180;
        if (cBoxQChildren.Checked == true && g < 4)
        {
            //push out the top 3 nodes, they should be returned by score in the json
            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.x + radius * System.Math.Cos(angle)) * 2;
            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle)) * 2;
        }
        else
        {
            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.y + radius * System.Math.Cos(angle));
            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle));
        }
        g = g + 1;
    }

    graphFile = new cn5apinet.GraphML.GraphMLFile(Application.StartupPath + "//" + node0.Text + ".graphml");
    graphFile.Create(nodeList, edgeList, Application.ProductName);

    System.Diagnostics.Process.Start(graphFile.FullPathLocation);
}
#endregion GraphML

Conclusion

ConceptNet REST API Continues to evolve and having a .Net interface is nice to explore ConceptNet with. It isn't the most efficient way to perform lookups [if you explore the ConceptNet5 website you can find alternative methods to perform queries (MongoDB 2.0 database and 24GB file of the json, etc)] but it is handy to code some proof of concept apps or just fiddling around in .Net learning about ConceptNet.

References

  • The ConceptNet Web API, Massachusetts Institute of Technology [^]
  • Newtonsoft.Json.dll, Json.NET Copyright (c) 2007 James Newton-King [^]
  • Open Mind Common Sense Project [^]

Updates

  • 12/17/11
    • Uploaded CNAPINetDemo v1.6.0.0 Microsoft Visual C# Express 2010 project files
    • Uploaded cn5apinet.dll v1.6.0.0 and necessary files.
  • 12/18/11
    • Uploaded CNAPINetDemo v1.6.0.0 Microsoft Visual C# Express 2010 project files with Json40r5 dll so manual download and reference add is no longer needed.
    • Misc article image tweaks.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

JoeSox

Network Administrator

United States United States

Member

Follow on Twitter Follow on Twitter
Born in Bristol PA, just north of Philadelphia. Joe has been programming since he was ten. He is entirely self-taught programmer, and he is currently working as a Network Administrator in Seattle WA. He is currently US Navy Active Reservist for (SPAWAR)
In '98 was honorably discharged from the USN. He served onboard the USS Carl Vinson (94-98) He was lucky enough to drink President Clinton's leftover wine, promoted by his Captain, and flew in a plane off the flightdeck but not all at the same time. His interests, when time allows, are developing
misc apps and Artificial Intelligence proof-of-concept demos that specifically exhibits human behavior. He is a true sports-a-holic, needs plenty of caffeine, and a coding junkie. He also enjoys alternative music and a big Pearl Jam, Nirvana, and new alternative music fan.
 
Joe owns the url www.humanaiproject.org[^]. He has submitted an abstract to DARPA in Dec 03 proposing his proposed HAI framework. Joe is an INTP[^] personality type. Joe "sees everything in terms of how it could be improved, or what it could be turned into. INTP's live primarily inside their own minds." INTPs also can have the "greatest precision in thought and language. Can readily discern contradictions and inconsistencies. The world exists primarily to be understood. 1% of the total population" [

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionGuess Mood Function Pinmembersabry.rizk0:51 18 Dec '11  
AnswerRe: Guess Mood Function PinmemberJoeSox3:35 18 Dec '11  
GeneralRe: Guess Mood Function Pinmembersabry.rizk8:34 24 Dec '11  
Questionpictures !!!! PinmemberYeurl_200723:10 17 Dec '11  
AnswerRe: pictures !!!! PinmemberJoeSox3:33 18 Dec '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 18 Dec 2011
Article Copyright 2011 by JoeSox
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid