コード例 #1
0
 public function search()
 {
     $validation = Validator::make(Input::all(), array('stackExchangeSearch' => 'required | max:50'));
     if ($validation->fails()) {
         return Redirect::back()->withInput()->withErrors($validation->messages());
     }
     $response = $this->getPosts(Input::get('stackExchangeSearch'), Input::get('count'));
     $alchemyapi = new AlchemyAPI();
     $postIntel = [];
     foreach ($response->items as $post) {
         $textOptions = ['useMetadata' => 1];
         $textResponse = $alchemyapi->text('url', $post->link, $textOptions);
         $sentimentOptions = ['sentiment' => 1];
         $postSentiment = $this->doAlchemy('url', $post->link, $sentimentOptions, 'sentiment', 'docSentiment', $alchemyapi);
         //Dont use concepts
         //when loading stack url into concepts call, it just returns random unrelated stuff
         //when loading extracted text into concepts call, it returns empty every time
         $entityOptions = ['maxRetrieve' => 5, 'sentiment' => 1];
         $postEntities = $this->doAlchemy('text', $textResponse['text'], $entityOptions, 'entities', 'entities', $alchemyapi);
         $keywordOptions = ['sentiment' => 1, 'showSourceText' => 1, 'maxRetrieve' => 5];
         $postKeywords = $this->doAlchemy('text', $textResponse['text'], $keywordOptions, 'keywords', 'keywords', $alchemyapi);
         $tmp = ['link' => $post->link, 'title' => $post->title, 'answered' => $post->is_answered, 'sentiment' => $postSentiment, 'entities' => $postEntities, 'keywords' => $postKeywords];
         array_push($postIntel, $tmp);
     }
     return View::make('stackResults')->with('postIntel', $postIntel)->with('searchTerm', Input::get('stackExchangeSearch'));
 }
コード例 #2
0
ファイル: textToSentiment.php プロジェクト: abapat/Tweemo-PHP
function getTweetSentiment($tweet)
{
    require_once 'Alchemy/alchemyapi_php/alchemyapi.php';
    $alchemyapi = new AlchemyAPI();
    //Object that represents the alchemy API
    $firstChar = $tweet[0];
    //Gets first character of the tweet
    $tweetSentiment = new sentiment();
    if ($firstChar == 'R' || $firstChar == '@') {
        //If it's retweet or mention, get to the meat of the tweet
        $colonIndex = strpos($tweet, ':');
        $tweet = substr($tweet, $colonIndex + 1);
    }
    try {
        $response = $alchemyapi->sentiment("text", $tweet, null);
        //Send a sentiment alchemy request
        if (strcmp($response['status'], "ERROR") != 0) {
            $tweetSentiment->type = $response['docSentiment']['type'];
            //Set the type
            if (strcmp($tweetSentiment->type, "neutral") == 0) {
                $tweetSentiment->score = 0.0;
            } else {
                $tweetSentiment->score = $response['docSentiment']['score'];
            }
            //Set the score
        }
    } catch (Exception $e) {
        echo 'Caught Exception: ', $e->getMessage(), "\n";
        //Catch the exception if the request breaks somehow
    }
    return $tweetSentiment;
    // return object
}
コード例 #3
0
 public function getTaxonomyFor($text)
 {
     $taxonomy = $this->alchemy->taxonomy('text', $text);
     $words = array();
     if (isset($taxonomy['taxonomy'])) {
         $total = 0;
         foreach ($taxonomy['taxonomy'] as $keyword) {
             $words[] = (string) $keyword['label'];
         }
     }
     return $words;
 }
コード例 #4
0
ファイル: Server.php プロジェクト: ashwin123/Article-Writer
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
// Keyword extraction
extract($_GET);
$res_arr = array();
$more_res = array();
$keywords = array();
$text = rawurldecode($demo_text);
$file_searched = fopen("search_terms.txt", "a+");
$size = filesize("search_terms.txt");
if ($size == 0) {
    $searched = array();
} else {
    $searched = fread($file_searched, filesize("search_terms.txt"));
    $searched = explode(";", $searched);
}
// $text = "Machine learning is a subfield of computer science that evolved from the study of pattern recognition and computational learning theory in artificial intelligence. Machine learning explores the study and construction of algorithms that can learn from and make predictions on data.";
$response = $alchemyapi->keywords('text', $text, array('maxRetrieve' => 2));
if ($response['status'] == 'OK') {
    $words = '';
    foreach ($response['keywords'] as $keyword) {
        //$words = $words . ';' . $keyword['text'] . ':' . $keyword['relevance'];
        $words = $words . ';' . $keyword['text'] . ':' . $keyword['relevance'];
        $keywords[$keyword['text']] = $keyword['relevance'];
    }
} else {
    echo 'Error in the keyword extraction call: ', $response['statusInfo'];
}
// $keywords = array('computational learning theory'=> '0.971245',
コード例 #5
0
 public function find_entities($message)
 {
     $alchemyapi = new \AlchemyAPI();
     $response = $alchemyapi->entities("text", $message, null);
     if ($response['status'] == 'OK') {
         /*//sort by relevance
           usort($response['entities'], function($a, $b) {
               return $a['relevance'] - $b['relevance'];
           });
           */
         return $response['entities'];
     } else {
         return null;
     }
 }
コード例 #6
0
ファイル: tests.php プロジェクト: fstream9/Slash
   Copyright 2013 AlchemyAPI

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$test_text = 'Bob broke my heart, and then made up this silly sentence to test the PHP SDK';
$test_html = '<html><head><title>The best SDK Test | AlchemyAPI</title></head><body><h1>Hello World!</h1><p>My favorite language is PHP</p></body></html>';
$test_url = 'http://www.nytimes.com/2013/07/13/us/politics/a-day-of-friction-notable-even-for-a-fractious-congress.html?_r=0';
$imageName = "grumpy-cat-meme-hmmm.jpg";
$imageFile = fopen($imageName, "r") or die("Unable to open file!");
$imageData = fread($imageFile, filesize($imageName));
fclose($imageFile);
//image keywords
echo 'Checking image keywords . . . ', PHP_EOL;
$response = $alchemyapi->image_keywords('url', $test_url, null);
assert($response['status'] == 'OK');
$response = $alchemyapi->image_keywords('image', $imageData, array('imagePostMode' => 'raw'));
assert($response['status'] == 'OK');
$response = $alchemyapi->image_keywords('random', $test_url, null);
assert($response['status'] == 'ERROR');
コード例 #7
0
}
$response3 = $alchemyapi3->sentiment("url", $myurl, null);
$s_de_socore = $response3["docSentiment"]["score"];
//echo $s_de_socore;
//fr
$alchemyapi3 = new AlchemyAPI();
if ($_SESSION["rawsearch"] == 0) {
    $myurl = $_SESSION["facedquery"] . "&fq=lang%3Afr";
} else {
    $myurl = "http://52.32.49.169:8983/solr/proj3/select?q=" . $translation_fr . "&fq=lang%3Afr" . "&start=0&rows=10&wt=json&indent=true";
}
$response3 = $alchemyapi3->sentiment("url", $myurl, null);
$s_fr_socore = $response3["docSentiment"]["score"];
//echo $s_fr_socore;
//ar
$alchemyapi3 = new AlchemyAPI();
if ($_SESSION["rawsearch"] == 0) {
    $myurl = $_SESSION["facedquery"] . "&fq=lang%3Aar";
} else {
    $myurl = "http://52.32.49.169:8983/solr/proj3/select?q=" . $translation_ar . "&fq=lang%3Aar" . "&start=0&rows=10&wt=json&indent=true";
}
$response3 = $alchemyapi3->sentiment("url", $myurl, null);
$s_ar_socore = $response3["docSentiment"]["score"];
//echo $s_ar_socore;
?>

                                                        <center>
                                                          <P>cultural differences of sentiment</P>
                                                        <script src="Chart.js"></script>
                                                      <style>
                                                        body{
コード例 #8
0
ファイル: language.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
/*include "../module/AlchemyAPI_CURL.php";*/
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Detect the language for a web URL.
$result = $alchemyObj->URLGetLanguage("http://www.techcrunch.fr/");
echo "{$result}<br/><br/>\n";
// Detect the language for a text string. (requires at least 100 characters text)
$result = $alchemyObj->TextGetLanguage("Hello my name is Bob Jones.  I am speaking to you at this very moment.  Are you listening to me, Bob?");
echo "{$result}<br/><br/>\n";
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Detect the language for a HTML document.
$result = $alchemyObj->HTMLGetLanguage($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
コード例 #9
0
 function render()
 {
     $sounds = array("A", "As", "B", "C", "Cs", "D", "Ds", "E", "F", "Fs", "G", "Gs");
     $paragraphs = array();
     //	build indexed array of dream values
     $dreams_by_value = array();
     foreach ($this->dreams as $dream) {
         if ($dream->node_type == self::TYPE_DREAM) {
             $index = array_search($dream, $this->dreams);
             $dreams_by_value[$index] = $dream->value;
         }
         if ($dream->value) {
             $sound_id = $sounds[floor(count($sounds) / 0xffffff * hexdec($dream->color2))];
             $sound_id .= min($dream->value, 3);
             $dream->soundeffect_path = $sound_id;
         }
     }
     //	sort array of values by value
     arsort($dreams_by_value);
     //	textualization
     $paragraphs[0] = array();
     $total_weight = 0;
     foreach ($dreams_by_value as $index => $value) {
         $total_weight += max(1, $this->dreams[$index]->value);
     }
     $cursor_position = 0;
     $i = 0;
     foreach ($dreams_by_value as $index => $value) {
         $dream = $this->dreams[$index];
         $sentences = preg_split("/(\\.+\\s*)/", $dream->description);
         $influence = max(1, $dream->value) / $total_weight;
         $excerpt_count = ceil($influence * count($sentences));
         $start = round(count($sentences) * $cursor_position);
         $length = min(count($sentences) - $start - 1, $excerpt_count);
         $excerpt = array_slice($sentences, $start, $length);
         $explanation = count($excerpt) . " sentences  taken from the " . $this->cardinalize($i + 1) . " most influential dream";
         for ($j = 0; $j < count($excerpt); $j++) {
             $paragraphs[0][] = array("index" => $dream->index, "sentence" => $sentences[$j], "explanation" => $explanation);
         }
         $cursor_position = ($start + $length) / count($sentences);
         $i++;
     }
     //	get alchemy tags for synthesized root node dynamically
     if (self::SHOW_TAGS) {
         //	flatten node content into a string
         $text = "";
         $sentences = array();
         foreach ($paragraphs as $p) {
             foreach ($p as $sentence) {
                 $sentences[] = $sentence['sentence'];
             }
         }
         $text = implode(". ", $sentences);
         //	alchemy
         $alchemy = new AlchemyAPI($this->alchemyApiKey);
         $params = array();
         $params['maxRetrieve'] = $this->maxKeywords;
         $params['keywordExtractMode'] = 'strict';
         $params['sentiment'] = 0;
         $params['showSourceText'] = 0;
         try {
             //	parse response
             $result = $alchemy->keywords('text', $text, $params);
         } catch (Exception $e) {
         }
         if (isset($result) && $result['status'] == "OK") {
             $root_node = $this->nodes[0];
             foreach ($result['keywords'] as $keyword) {
                 $tag = stripslashes($keyword['text']);
                 $tag = preg_replace("/\\./", "", $tag);
                 if (isset($this->indexes['tags'][$tag])) {
                     $tag_node = $this->indexes['tags'][$tag];
                 } else {
                     $this->indexes['tags'][$tag] = $this->tags[] = $tag_node = (object) array('color' => '#000000', 'id' => -1, 'index' => count($this->nodes), 'node_type' => 'tag', 'tags' => array(), 'title' => $tag, 'value' => 0);
                 }
                 if ($tag_node->value >= $this->minTagValue) {
                     if (!array_search($tag_node, $this->nodes)) {
                         $this->nodes[] = $tag_node;
                     }
                     $this->addTag($tag_node, $root_node);
                 }
             }
         }
     }
     $this->nodes[0]->description = $paragraphs;
     foreach ($this->nodes as $node) {
         if ($node->node_type == self::TYPE_TAG || $node->node_type == self::TYPE_DREAM && (isset($node->ip) && $node->ip == $_SERVER['REMOTE_ADDR'])) {
             $node->stroke = true;
         } else {
             $node->stroke = $node->strokeContrast = isset($node->color2) ? hexdec(preg_replace("/#/", "0x", $node->color2)) < 0x666666 ? true : false : false;
         }
     }
     $data = (object) array('nodes' => $this->nodes, 'links' => $this->links, 'dream_total' => count($this->dreams), 'art_total' => 0);
     return $data;
 }
コード例 #10
0
ファイル: self.php プロジェクト: AyushYadav/alchemyapi_php
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI('YOUR_API_KEY');
$demo_text = 'From US to China, international powers criticise North Korea hydrogen bomb test';
echo PHP_EOL;
echo PHP_EOL;
echo PHP_EOL;
echo '############################################', PHP_EOL;
echo '#   Keyword Extraction Example             #', PHP_EOL;
echo '############################################', PHP_EOL;
echo PHP_EOL;
echo PHP_EOL;
echo 'Processing text: ', $demo_text, PHP_EOL;
echo PHP_EOL;
$response = $alchemyapi->keywords('text', $demo_text, array('sentiment' => 1));
if ($response['status'] == 'OK') {
    echo '## Response Object ##', PHP_EOL;
    echo print_r($response);
    echo PHP_EOL;
    echo '## Keywords ##', PHP_EOL;
    foreach ($response['keywords'] as $keyword) {
        echo 'keyword: ', $keyword['text'], PHP_EOL;
        // echo 'relevance: ', $keyword['relevance'], PHP_EOL;
        // echo 'sentiment: ', $keyword['sentiment']['type'];
        // if (array_key_exists('score', $keyword['sentiment'])) {
        // 	echo ' (' . $keyword['sentiment']['score'] . ')', PHP_EOL;
        // } else {
        // 	echo PHP_EOL;
        // }
        echo PHP_EOL;
コード例 #11
0
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
extract($_GET);
$url = rawurldecode($url);
$response = $alchemyapi->text('url', $url, null);
if ($response['status'] == 'OK') {
    $content = explode(".", $response['text'], 1);
    $retstr = implode(".", $content);
    echo $retstr;
} else {
    echo 'Error in the text extraction call: ', $response['statusInfo'];
}
コード例 #12
0
ファイル: dream.class.php プロジェクト: npedrini/artefacts
 public function save($validate = true)
 {
     $this->logger->clear();
     //	validation
     $valid = !$validate || $this->validate();
     //	get a user_id, either by adding new user or fetching id of existing
     if ($valid) {
         $user = new User(null, $this->db);
         $user->email = $this->email;
         $user->name = $this->username;
         if (!is_null($user->email) && !empty($user->email)) {
             $user->loadFromEmail();
         } else {
             if (!is_null($user->name) && !empty($user->name)) {
                 $user->loadFromName();
             }
         }
         if ($this->isImport) {
             $user->implied = 1;
         }
         if ($user->id) {
             $this->logger->log("user found...");
         } else {
             $user->ip = $_SERVER['REMOTE_ADDR'];
         }
         $success = $user->save();
         $this->user_id = $user->id;
         if (is_null($this->user_id)) {
             $valid = false;
         }
     }
     if ($valid && isset($this->imageUpload) && !empty($this->imageUpload["name"]) && $this->imageUpload["error"] == 0) {
         $this->logger->log("saving image...");
         $image = new Media(null, $this->db);
         $image->name = time();
         $image->mime_type = $this->imageUpload['type'];
         $image->tempFile = $this->imageUpload;
         if ($image->validate()) {
             if ($image->save()) {
                 $this->logger->log("image saved...");
             } else {
                 $this->status = $image->errorMessage;
                 $valid = false;
                 $this->logger->log("error saving image...");
             }
         } else {
             $this->status = $image->errorMessage;
             $valid = false;
         }
     }
     if ($valid && isset($this->audioUpload) && !empty($this->audioUpload["name"]) && $this->audioUpload["error"] == 0) {
         $this->logger->log("saving audio...");
         $audio = new Media(null, $this->db);
         $audio->name = time();
         $audio->mime_type = $this->audioUpload['type'];
         $audio->tempFile = $this->audioUpload;
         if ($audio->validate()) {
             if ($audio->save()) {
                 $this->logger->log("audio saved...");
             } else {
                 $this->status = $audio->errorMessage;
                 $valid = false;
                 $this->logger->log("error saving audio...");
             }
         } else {
             $this->status = $audio->errorMessage;
             $valid = false;
             $this->logger->log("error validating audio...");
         }
     }
     $get_location = curl_init();
     curl_setopt($get_location, CURLOPT_URL, "http://freegeoip.net/json/" . $_SERVER['REMOTE_ADDR']);
     curl_setopt($get_location, CURLOPT_RETURNTRANSFER, 1);
     $location = curl_exec($get_location);
     $location = json_decode($location);
     //	import dream
     if ($valid) {
         $date = DateTime::createFromFormat($this->dateFormat, $this->date, new DateTimeZone($this->timezone));
         $this->occur_date = $date->format('Y-m-d');
         if ($location) {
             $this->city = $location->city;
             $this->country = $location->country_name;
             $this->latitude = $location->latitude;
             $this->longitude = $location->longitude;
         } else {
             $this->latitude = "0";
             $this->longitude = "0";
         }
         $success = parent::save();
         if ($success) {
             $this->status = "Dream added!";
         } else {
             if (isset($this->errorMessage)) {
                 $this->status = $this->errorMessage;
             } else {
                 $this->status = "Error updating dream";
             }
             $valid = false;
         }
     }
     if (isset($image)) {
         if (!is_null($this->id) && !empty($this->id)) {
             $image->dream_id = $this->id;
             $image->save();
         } else {
             $image->delete();
         }
         $this->logger->log($image->logger->log);
     }
     if (isset($audio)) {
         if (!is_null($this->id) && !empty($this->id)) {
             $audio->dream_id = $this->id;
             $audio->save();
         } else {
             $audio->delete();
         }
         $this->logger->log($audio->logger->log);
     }
     $tags = array();
     //	add dream tags
     if ($valid && $this->useAlchemy) {
         $kb = strlen($this->description) / 1024;
         if ($kb <= 150) {
             $alchemy = new AlchemyAPI($this->alchemyApiKey);
             $params = array();
             $params['maxRetrieve'] = 20;
             $params['keywordExtractMode'] = 'strict';
             $params['sentiment'] = 1;
             $params['showSourceText'] = 0;
             try {
                 $result = $alchemy->keywords('text', $this->description, $params);
                 $this->logger->log("alchemy " . $result['status'] . ", " . (isset($result['keywords']) ? count($result['keywords']) : 0) . " keywords, " . $this->description);
             } catch (Exception $e) {
                 $this->logger->log("alchemy, " . $result['status'] . ", " . $result['statusInfo']);
             }
             if (isset($result) && $result['status'] == "OK") {
                 foreach ($result['keywords'] as $keyword) {
                     $tag = stripslashes($keyword['text']);
                     $tag = preg_replace("/^\\W|\\W\$|\\./", "", $tag);
                     $tag = strtolower(trim($tag));
                     $tag = $this->db->real_escape_string($tag);
                     //	get tag_id
                     $sql = "SELECT id FROM `tags` WHERE tag='" . $tag . "'";
                     $result2 = $this->db->query($sql);
                     if ($this->db->affected_rows > 0) {
                         $tag_row = $result2->fetch_assoc();
                         $tag_id = $tag_row['id'];
                     } else {
                         $sql = "INSERT INTO `tags` (tag,alchemy) VALUES ('" . $tag . "','1')";
                         $this->db->query($sql);
                         $tag_id = $this->db->insert_id;
                     }
                     if ($tag_id) {
                         $sentiment = $keyword['sentiment'];
                         $sql = "INSERT INTO `dream_tags` (dream_id,tag_id,sentiment_type,sentiment_score) VALUES ('" . $this->id . "','" . $tag_id . "','" . $sentiment['type'] . "','" . (isset($sentiment['score']) ? $sentiment['score'] : 0) . "')";
                         $this->db->query($sql);
                     }
                     $tags[] = $tag;
                 }
             }
         } else {
             $this->logger->log("Dream " . $this->id . " to big to process" . $kb);
         }
     }
     if ($valid && $this->postToTumblr && $this->tumblrPostEmail != null) {
         $to = $this->tumblrPostEmail;
         $subject = isset($this->title) ? $this->title : "untitled";
         $body = $this->description;
         $body .= "\n\nDreamt on " . $this->date . " by a " . $this->age . " year old " . ($this->gender == "male" ? "man" : "woman") . " in " . $location->city;
         $body .= "\n\nhttp://artefactsofthecollectiveunconscious.net/browse.php?did=" . $this->id;
         $tagline = '';
         foreach ($tags as $tag) {
             $tagline .= "#" . $tag . " ";
         }
         $body .= "\n\n" . $tagline;
         mail($to, $subject, $body);
     }
     if ($valid) {
         foreach ($this->feelings as $feeling_id) {
             if ($feeling_id) {
                 $sql = "INSERT INTO `dream_feelings` (dream_id,feeling_id) VALUES ('" . $this->id . "','" . $feeling_id . "')";
                 $result = $this->db->query($sql);
             }
         }
     }
     if ($valid) {
         $this->init();
     }
     return $valid;
 }
コード例 #13
0
            </div>
            
            <input type="submit" class="btn btn-success btn-lg" name="submit" value="Submit Query"/>
          </form>
        </div>
      </div>
    </div>-->
    
    <div class="container"> 
      <!--<textarea class="form-control" placeholder="Your output.." rows="50"><?php 
/*print_r($json);*/
?>
</textarea>-->
      <?php 
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$i = 0;
$counter = 0;
$itemName = "";
$current = array();
$inner = array();
$outer = $inner;
echo '<p class="alert alert-success searchDisplayer">Search results for "' . $query . '". Total search items retrieved: ' . $json['response']['numFound'] . '</p>';
//echo '<p class="alert alert-success searchDisplayer">'.$finalQuery.'</p>';
//print_r($_SESSION['facetArray']);
echo '<div class="major_div">';
echo '<div class="facet_div">';
$intC = 0;
echo '<ul class="list-group ul_class facet_ul">';
if ($json['facet_counts']['facet_fields']['tweet_hashtags']) {
    echo '<a href="#li_hide" data-toggle="collapse" class="facet_link"><p class="facet_head">Search by choosing Hashtags<span class="glyphicon glyphicon-chevron-down facet_arrow"></span></p></a>';
コード例 #14
0
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$response = $alchemyapi->keywords('text', "Oh, love of mine\nWith a song and a whine\nYou're harsh and divine\nLike truths and a lie\n\nBut the tale ends not here\nI have nothing to fear\nFor my love is yell of giving and hold on\n\nAnd the bright emptiness\nIn a room full of it\nIs a cruel mistress\nWhoa oh!", array('sentiment' => 1));
foreach ($response['keywords'] as $keyword) {
    echo $keyword['text'], PHP_EOL;
    echo "<br />";
}
コード例 #15
0
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI('YOUR_API_KEY');
$DATA = 'Any news';
//the news goes in here
$FLAVOR = 'text';
$response = $alchemyapi->keywords($FLAVOR, $DATA, array('sentiment' => 0));
// $response = $alchemyapi->keywords('text', 'Bunnies are nice but sometimes robots are evil', array('sentiment'=>1));
foreach ($response['keywords'] as $keyword) {
    echo $keyword['text'], PHP_EOL;
}
コード例 #16
0
ファイル: nlp.php プロジェクト: imshashank/the_game_choice
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$demo_text = 'Yesterday dumb Bob destroyed my fancy iPhone in beautiful Denver, Colorado. I guess I will have to head over to the Apple Store and buy a new one.';
$response = $alchemyapi->category('text', $demo_text, null);
if ($response['status'] == 'OK') {
    echo print_r($response);
    echo 'category: ', $response['category'], PHP_EOL;
    echo 'score: ', $response['score'], PHP_EOL;
} else {
    echo 'Error in the text categorization call: ', $response['statusInfo'];
}
コード例 #17
0
ファイル: sentiment.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
/*include "../module/AlchemyAPI_CURL.php";*/
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Extract sentiment from a web URL.
$result = $alchemyObj->URLGetTextSentiment("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Extract sentiment from a text string.
$result = $alchemyObj->TextGetTextSentiment("It's wonderful when the sun is shining and ABBA is playing.");
echo "{$result}<br/><br/>\n";
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Extract sentiment from a HTML document.
$result = $alchemyObj->HTMLGetTextSentiment($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
// Enable entity-level sentiment.
$namedEntityParams = new AlchemyAPI_NamedEntityParams();
$namedEntityParams->setSentiment(1);
// Extract entities with entity-level sentiment.
$result = $alchemyObj->TextGetRankedNamedEntities("Wyle E. Coyote is slow.", "xml", $namedEntityParams);
echo "{$result}<br/><br/>\n";
// Enable keyword-level sentiment.
$keywordParams = new AlchemyAPI_KeywordParams();
$keywordParams->setSentiment(1);
// Extract keywords with keyword-level sentiment.
コード例 #18
0
ファイル: example.php プロジェクト: khromov/alchemyapi_php
   Copyright 2013 AlchemyAPI

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$demo_text = 'Yesterday dumb Bob destroyed my fancy iPhone in beautiful Denver, Colorado. I guess I will have to head over to the Apple Store and buy a new one.';
$demo_url = 'http://www.npr.org/2013/11/26/247336038/dont-stuff-the-turkey-and-other-tips-from-americas-test-kitchen';
$demo_html = '<html><head><title>PHP Demo | AlchemyAPI</title></head><body><h1>Did you know that AlchemyAPI works on HTML?</h1><p>Well, you do now.</p></body></html>';
echo PHP_EOL;
echo PHP_EOL;
echo '            ,                                                                                                                              ', PHP_EOL;
echo '      .I7777~                                                                                                                              ', PHP_EOL;
echo '     .I7777777                                                                                                                             ', PHP_EOL;
echo '   +.  77777777                                                                                                                            ', PHP_EOL;
echo ' =???,  I7777777=                                                                                                                          ', PHP_EOL;
echo '=??????   7777777?   ,:::===?                                                                                                              ', PHP_EOL;
echo '=???????.  777777777777777777~         .77:    ??           :7                                              =$,     :$$$$$$+  =$?          ', PHP_EOL;
echo ' ????????: .777777777777777777         II77    ??           :7                                              $$7     :$?   7$7 =$?          ', PHP_EOL;
echo '  .???????=  +7777777777777777        .7 =7:   ??   :7777+  :7:I777?    ?777I=  77~777? ,777I I7      77   +$?$:    :$?    $$ =$?          ', PHP_EOL;
echo '    ???????+  ~777???+===:::         :7+  ~7   ?? .77    +7 :7?.   II  7~   ,I7 77+   I77   ~7 ?7    =7:  .$, =$    :$?  ,$$? =$?          ', PHP_EOL;
コード例 #19
0
	<span id="sl_i3" class="sl_command sl_i">&nbsp;</span>
	<span id="sl_i4" class="sl_command sl_i">&nbsp;</span>
	
	<h2 class="sread">The slideshow</h2>
	<div class="lyrics" style=" color:#FFF;  font-family:Verdana, Geneva, sans-serif;margin-top:30px;margin-bottom:20px;"><hr />
    
<?php 
$id = $_GET["trackid"];
// To get lyrics
$url = "http://api.musixmatch.com/ws/1.1/track.lyrics.get?apikey=76bda465128468ccea51f3ad58f3fcdd&track_id=" . $id . "&format=xml";
$xml = simplexml_load_file($url);
$value = (string) $xml->body->lyrics->lyrics_body;
print_r($value);
//to get meaning
require_once 'alchemyapi_php-master/alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$response = $alchemyapi->keywords('text', "{$value}", array('sentiment' => 1));
?>

<!-- Start WOWSlider.com BODY section --> <!-- add to the <body> of your page -->
	<div id="wowslider-container0">
	<div class="ws_images"><ul>
		
	
	

	
<?php 
$i = 0;
foreach ($response['keywords'] as $keyword) {
    //displaying images
コード例 #20
0
ファイル: relations.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
//include "../module/AlchemyAPI_CURL.php";
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Extract a ranked list of relations from a web URL.
$result = $alchemyObj->URLGetRelations("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Extract a ranked list of relations from a text string.
$result = $alchemyObj->TextGetRelations("Hello my name is Bob.  I am speaking to you at this very moment.  Are you listening to me, Bob?");
echo "{$result}<br/><br/>\n";
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Extract a ranked list of relations from a HTML document.
$result = $alchemyObj->HTMLGetRelations($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
$relationParams = new AlchemyAPI_RelationParams();
// Turn off quotations extraction
$relationParams->SetSentiment(1);
$relationParams->SetEntities(1);
$relationParams->SetDisambiguate(1);
$relationParams->SetSentimentExcludeEntities(1);
$result = $alchemyObj->TextGetRelations("Madonna enjoys tasty Pepsi.  I love her style.", "xml", $relationParams);
echo "{$result}<br/><br/>\n";
$relationParams->SetRequireEntities(1);
$result = $alchemyObj->TextGetRelations("Madonna enjoys tasty Pepsi.  I love her style.", "xml", $relationParams);
コード例 #21
0
ファイル: authors.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
/*include "../module/AlchemyAPI_CURL.php";*/
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Extract concept tags from a web URL.
//$result = $alchemyObj->URLGetRankedConcepts("http://www.techcrunch.com/");
$result = $alchemyObj->URLGetAuthor("http://www.politico.com/blogs/media/2012/02/detroit-news-ed-upset-over-romney-edit-115247.html");
echo "{$result}<br/><br/>\n";
$result = $alchemyObj->HTMLGetAuthor($htmlFile, "http://www.test.com");
echo "{$result}<br/><br/>\n";
コード例 #22
0
<?php

$file = file_get_contents('../all.txt', true);
require_once '../alchemyapi/alchemyapi.php';
$alchemyapi = new AlchemyAPI();
?>

<?php 
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(array('label' => 'text', 'type' => 'string'), array('label' => 'sentiment', 'type' => 'string'), array('label' => 'relevance', 'type' => 'number'));
$rows = array();
$response = $alchemyapi->keywords('text', $file, array('sentiment' => 1));
foreach ($response['keywords'] as $keyword) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $keyword['text']);
    $temp[] = array('v' => (string) $keyword['sentiment']['type']);
    // Values of each slice
    $temp[] = array('v' => (double) $keyword['relevance']);
    $rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>


<html>
コード例 #23
0
<?php

require_once 'alch/alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$demo_text = $_GET['text'];
$result = array();
$response = $alchemyapi->taxonomy('text', $demo_text, null);
if ($response['status'] == 'OK') {
    #echo '## Response Object ##', PHP_EOL;
    #echo print_r($response);
    #echo PHP_EOL;
    #echo '## Categories ##', PHP_EOL;
    $i = 0;
    foreach ($response['taxonomy'] as $category) {
        $x = explode('/', $category['label']);
        foreach ($x as $y) {
            if (!isset($result[$y]) && $y != '') {
                $result[$y] = $category['score'];
            }
        }
        $i = $i + 1;
        #echo $category['label'], ' : ', $category['score'], PHP_EOL;
    }
}
#$res = json_decode($output, true);
echo json_encode($result);
コード例 #24
0
ファイル: text_extract.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
/*include "../module/AlchemyAPI_CURL.php";*/
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Extract a title from a web URL.
$result = $alchemyObj->URLGetTitle("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Extract page text from a web URL (ignoring navigation links, ads, etc.).
$result = $alchemyObj->URLGetText("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Extract raw page text from a web URL (including navigation links, ads, etc.).
$result = $alchemyObj->URLGetRawText("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Extract a title from a HTML document.
$result = $alchemyObj->HTMLGetTitle($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
// Extract page text from a HTML document (ignoring navigation links, ads, etc.).
$result = $alchemyObj->HTMLGetText($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
// Extract raw page text from a HTML document (including navigation links, ads, etc.).
$result = $alchemyObj->HTMLGetRawText($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
コード例 #25
0
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
extract($_GET);
$res_arr = array();
$text = rawurldecode($demo_text);
//echo $text;
//$text_arr = explode(" ",$text);
$response = $alchemyapi->concepts('text', $text, array('maxRetrieve' => 2));
if ($response['status'] == 'OK') {
    $con = array();
    // if(isset($response['concepts']))
    // 	echo "set";
    // echo json_encode($response);
    foreach ($response['concepts'] as $concept) {
        //array_push($concepts, $concept['text']);
        $con[$concept['text']] = $concept['relevance'];
        // echo $concept['relevance'];
    }
} else {
    echo 'Error in the concept tagging call: ', $response['statusInfo'];
}
// $con = array('computational learning theory'=> '0.971245',
// 				'Computer'=> '0.854866',
// 				'artificial intelligence'=> '0.793011',
// 				'Machine learning' => '0.714784',
// 				'subfield'=> '0.638192');
arsort($con);
$concept = array_keys($con)[0];
// echo $concept;
コード例 #26
0
ファイル: feed.php プロジェクト: roka371/Infograph
 function extract_keyword($content, $permalink)
 {
     // Set up the text to analyze keyword.
     // If the length of the feed is not up to quality standards, track down and load the actual article.
     if (strlen(strip_tags($content)) < 500) {
         $extracted_text = $this->feed_hunter($permalink)->text;
         // Make sure the newly loaded feed is up to quality standards.
         if (strlen(strip_tags($content)) > 500) {
             $specimen = $extracted_text;
         } else {
             $specimen = strip_tags($content);
         }
     } else {
         $specimen = strip_tags($content);
     }
     $characters = array('"');
     $replacements = array(' ');
     $text = str_replace($characters, $replacements, $specimen);
     // Load the AlchemyAPI and configure access key.
     require_once 'inc/AlchemyAPI.php';
     $alchemyObj = new AlchemyAPI();
     $alchemyObj->setAPIKey("1414657c7c56cc31a067f8daafabf1d6978c28fe");
     // Analyze the article, fetching the concept, keyword, and category of an article.
     $tags_json = json_decode($alchemyObj->TextGetRankedKeywords($text, 'json'));
     $concepts_json = json_decode($alchemyObj->TextGetRankedConcepts($text, 'json'));
     $category = json_decode($alchemyObj->TextGetCategory($text, 'json'));
     $this->feed_model->alchemy_meter(3);
     // Parse the result retrieved from AlchemyAPI into an associated array.
     $tags = array();
     foreach ($concepts_json->concepts as $concept) {
         $characters = array("'");
         $replacements = array("");
         $output = str_replace($characters, $replacements, $concept->text);
         $tag['keyword'] = $output;
         $tag['confidence'] = $concept->relevance;
         $tag['is_concept'] = TRUE;
         array_push($tags, $tag);
     }
     foreach ($tags_json->keywords as $keyword) {
         $characters = array("'");
         $replacements = array("");
         $output = str_replace($characters, $replacements, $keyword->text);
         $tag['keyword'] = $output;
         $tag['confidence'] = $keyword->relevance;
         $tag['is_concept'] = FALSE;
         array_push($tags, $tag);
     }
     // Return the result.
     $result['tags'] = $tags;
     $result['category'] = $category->category;
     return $result;
 }
コード例 #27
0
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$feed_url = "http://www.the-star.co.ke/star-health";
$content = file_get_contents($feed_url, true);
$feed = json_decode($content);
if (property_exists($feed, "nodes") && isFresh($content)) {
    //first dump raw content to file to check if new in subsequent pulls
    file_put_contents("oldsha.txt", sha1($content));
    $items = $feed->nodes;
    $articles = array();
    $concepts = array();
    foreach ($items as $d) {
        $item = $d->node;
        $response = $alchemyapi->concepts('text', $item->body, null);
        $tags = array();
        $weighted_tags = array();
        if ($response['status'] == 'OK') {
            foreach ($response['concepts'] as $concept) {
                if (!array_key_exists($concept['text'], $tags)) {
                    //No exact match
                    //check if this key is substring of existing key or vice versa
                    $existing_key = sub_exists($concept['text'], $concepts);
                    if ($existing_key != null) {
                        $new_value = $concepts[$existing_key] + 1;
                        $concepts[$existing_key] = $new_value;
                        $tags[] = $existing_key;
                    } else {
                        $concepts[$concept['text']] = 1;
                        $tags[] = $concept['text'];
コード例 #28
0
ファイル: feed_links.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
/*include "../module/AlchemyAPI_CURL.php";*/
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Extract RSS / ATOM feed links from a web URL.
$result = $alchemyObj->URLGetFeedLinks("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Extract RSS / ATOM feed links from a HTML document.
$result = $alchemyObj->HTMLGetFeedLinks($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";
コード例 #29
0
ファイル: example.php プロジェクト: Laradev/sdk_php
<?php

require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI();
$demo_text = 'Yesterday dumb Bob destroyed my fancy iPhone in beautiful Denver, Colorado. I guess I will have to head over to the Apple Store and buy a new one.';
$demo_url = 'http://blog.programmableweb.com/2011/09/16/new-api-billionaire-text-extractor-alchemy/';
$demo_html = '<html><head><title>Python Demo | AlchemyAPI</title></head><body><h1>Did you know that AlchemyAPI works on HTML?</h1><p>Well, you do now.</p></body></html>';
echo PHP_EOL;
echo PHP_EOL;
echo '            ,                                                                                                                              ', PHP_EOL;
echo '      .I7777~                                                                                                                              ', PHP_EOL;
echo '     .I7777777                                                                                                                             ', PHP_EOL;
echo '   +.  77777777                                                                                                                            ', PHP_EOL;
echo ' =???,  I7777777=                                                                                                                          ', PHP_EOL;
echo '=??????   7777777?   ,:::===?                                                                                                              ', PHP_EOL;
echo '=???????.  777777777777777777~         .77:    ??           :7                                              =$,     :$$$$$$+  =$?          ', PHP_EOL;
echo ' ????????: .777777777777777777         II77    ??           :7                                              $$7     :$?   7$7 =$?          ', PHP_EOL;
echo '  .???????=  +7777777777777777        .7 =7:   ??   :7777+  :7:I777?    ?777I=  77~777? ,777I I7      77   +$?$:    :$?    $$ =$?          ', PHP_EOL;
echo '    ???????+  ~777???+===:::         :7+  ~7   ?? .77    +7 :7?.   II  7~   ,I7 77+   I77   ~7 ?7    =7:  .$, =$    :$?  ,$$? =$?          ', PHP_EOL;
echo '    ,???????~                        77    7:  ?? ?I.     7 :7     :7 ~7      7 77    =7:    7  7    7~   7$   $=   :$$$$$$~  =$?          ', PHP_EOL;
echo '    .???????  ,???I77777777777~     :77777777~ ?? 7:        :7     :7 777777777:77    =7     7  +7  ~7   $$$$$$$$I  :$?       =$?          ', PHP_EOL;
echo '   .???????  ,7777777777777777      7=      77 ?? I+      7 :7     :7 ??      7,77    =7     7   7~ 7,  =$7     $$, :$?       =$?          ', PHP_EOL;
echo '  .???????. I77777777777777777     +7       ,7???  77    I7 :7     :7  7~   .?7 77    =7     7   ,77I   $+       7$ :$?       =$?          ', PHP_EOL;
echo ' ,???????= :77777777777777777~     7=        ~7??  ~I77777  :7     :7  ,777777. 77    =7     7    77,  +$        .$::$?       =$?          ', PHP_EOL;
echo ',???????  :7777777                                                                                77                                       ', PHP_EOL;
echo ' =?????  ,7777777                                                                               77=                                        ', PHP_EOL;
echo '   +?+  7777777?                                                                                                                           ', PHP_EOL;
echo '    +  ~7777777                                                                                                                            ', PHP_EOL;
echo '       I777777                                                                                                                             ', PHP_EOL;
echo '          :~                                                                                                                               ', PHP_EOL;
echo PHP_EOL;
コード例 #30
0
ファイル: concepts.php プロジェクト: radicalsuz/fe
<?php

// Load the AlchemyAPI module code.
include "../module/AlchemyAPI.php";
// Or load the AlchemyAPI PHP+CURL module.
/*include "../module/AlchemyAPI_CURL.php";*/
// Create an AlchemyAPI object.
$alchemyObj = new AlchemyAPI();
// Load the API key from disk.
$alchemyObj->loadAPIKey("api_key.txt");
// Extract concept tags from a web URL.
$result = $alchemyObj->URLGetRankedConcepts("http://www.techcrunch.com/");
echo "{$result}<br/><br/>\n";
// Extract concept tags from a text string.
$result = $alchemyObj->TextGetRankedConcepts("This thing has a steering wheel, tires, and an engine.  Do you know what it is?");
echo "{$result}<br/><br/>\n";
// Load a HTML document to analyze.
$htmlFile = file_get_contents("data/example.html");
// Extract concept tags from a HTML document.
$result = $alchemyObj->HTMLGetRankedConcepts($htmlFile, "http://www.test.com/");
echo "{$result}<br/><br/>\n";