|
| 1 | +# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, |
| 10 | +# software distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# flake8: noqa |
| 16 | + |
| 17 | +""" |
| 18 | +Script to analyze the sentiment of a given file of tweets from Twitter |
| 19 | +in batch processing mode. |
| 20 | +
|
| 21 | +########## |
| 22 | +Command help: |
| 23 | +Usage: analyze_sentiment.py [OPTIONS] |
| 24 | +
|
| 25 | + Analyze the sentiment of the tweets given in the tweets_file and print out |
| 26 | + the results. |
| 27 | +
|
| 28 | +Options: |
| 29 | + --model_path TEXT The path to the sentiment analysis model to |
| 30 | + load.Either a model.onnx file, a model folder |
| 31 | + containing the model.onnx and supporting files, or a |
| 32 | + SparseZoo model stub. |
| 33 | + --tweets_file TEXT The path to the tweets json txt file to analyze |
| 34 | + sentiment for. |
| 35 | + --batch_size INTEGER The batch size to process the tweets with. A higher |
| 36 | + batch size may increase performance at the expense |
| 37 | + of memory resources and individual latency. |
| 38 | + --total_tweets INTEGER The total number of tweets to analyze from the |
| 39 | + tweets_file.Defaults to None which will run through |
| 40 | + all tweets contained in the file. |
| 41 | + --help Show this message and exit. |
| 42 | +
|
| 43 | +########## |
| 44 | +Example running a sparse, quantized sentiment analysis model: |
| 45 | +python analyze_sentiment.py |
| 46 | + --model_path "zoo:nlp/sentiment_analysis/bert-base/pytorch/huggingface/sst2/12layer_pruned80_quant-none-vnni" |
| 47 | + --tweets_file /PATH/TO/OUTPUT/FROM/scrape.py |
| 48 | +
|
| 49 | +########## |
| 50 | +Example running a dense, unoptimized sentiment analysis model: |
| 51 | +python analyze_sentiment.py |
| 52 | + --model_path "zoo:nlp/sentiment_analysis/bert-base/pytorch/huggingface/sst2/base-none" |
| 53 | + --tweets_file /PATH/TO/OUTPUT/FROM/scrape.py |
| 54 | +""" |
| 55 | + |
| 56 | +import json |
| 57 | +from itertools import cycle, islice |
| 58 | +from typing import Any, Dict, List, Optional |
| 59 | + |
| 60 | +import click |
| 61 | + |
| 62 | +from deepsparse.transformers import pipeline |
| 63 | +from rich import print |
| 64 | + |
| 65 | + |
| 66 | +def _load_tweets(tweets_file: str): |
| 67 | + tweets = [] |
| 68 | + with open(tweets_file, "r") as file: |
| 69 | + for line in file.readlines(): |
| 70 | + tweets.append(json.loads(line)) |
| 71 | + |
| 72 | + return tweets |
| 73 | + |
| 74 | + |
| 75 | +def _prep_data(tweets: List[Dict], total_num: int) -> List[str]: |
| 76 | + if total_num: |
| 77 | + tweets = islice(cycle(tweets), total_num) |
| 78 | + |
| 79 | + return [tweet["tweet"].strip().replace("\n", "") for tweet in tweets] |
| 80 | + |
| 81 | + |
| 82 | +def _batched_model_input(tweets: List[str], batch_size: int) -> Optional[List[str]]: |
| 83 | + if batch_size >= len(tweets): |
| 84 | + return None |
| 85 | + |
| 86 | + batched = tweets[0:batch_size] |
| 87 | + del tweets[0:batch_size] |
| 88 | + |
| 89 | + return batched |
| 90 | + |
| 91 | + |
| 92 | +def _classified_positive(sentiment: Dict[str, Any]): |
| 93 | + return sentiment["label"] == "LABEL_1" |
| 94 | + |
| 95 | + |
| 96 | +def _display_results(batch, sentiments): |
| 97 | + for text, sentiment in zip(batch, sentiments): |
| 98 | + color = "green" if _classified_positive(sentiment) else "magenta" |
| 99 | + print(f"[{color}]{text}[/{color}]") |
| 100 | + |
| 101 | + |
| 102 | +@click.command() |
| 103 | +@click.option( |
| 104 | + "--model_path", |
| 105 | + type=str, |
| 106 | + help="The path to the sentiment analysis model to load." |
| 107 | + "Either a model.onnx file, a model folder containing the model.onnx " |
| 108 | + "and supporting files, or a SparseZoo model stub.", |
| 109 | +) |
| 110 | +@click.option( |
| 111 | + "--tweets_file", |
| 112 | + type=str, |
| 113 | + help="The path to the tweets json txt file to analyze sentiment for.", |
| 114 | +) |
| 115 | +@click.option( |
| 116 | + "--batch_size", |
| 117 | + type=int, |
| 118 | + default=16, |
| 119 | + help="The batch size to process the tweets with. " |
| 120 | + "A higher batch size may increase performance at the expense of memory resources " |
| 121 | + "and individual latency.", |
| 122 | +) |
| 123 | +@click.option( |
| 124 | + "--total_tweets", |
| 125 | + type=int, |
| 126 | + default=None, |
| 127 | + help="The total number of tweets to analyze from the tweets_file." |
| 128 | + "Defaults to None which will run through all tweets contained in the file.", |
| 129 | +) |
| 130 | +def analyze_tweets_sentiment( |
| 131 | + model_path: str, tweets_file: str, batch_size: int, total_tweets: int |
| 132 | +): |
| 133 | + """ |
| 134 | + Analyze the sentiment of the tweets given in the tweets_file and |
| 135 | + print out the results. |
| 136 | + """ |
| 137 | + text_pipeline = pipeline( |
| 138 | + task="text-classification", |
| 139 | + model_path=model_path, |
| 140 | + batch_size=batch_size, |
| 141 | + ) |
| 142 | + tweets = _load_tweets(tweets_file) |
| 143 | + tweets = _prep_data(tweets, total_tweets) |
| 144 | + tot_sentiments = [] |
| 145 | + |
| 146 | + while True: |
| 147 | + batch = _batched_model_input(tweets, batch_size) |
| 148 | + if batch is None: |
| 149 | + break |
| 150 | + sentiments = text_pipeline(batch) |
| 151 | + _display_results(batch, sentiments) |
| 152 | + tot_sentiments.extend(sentiments) |
| 153 | + |
| 154 | + num_positive = sum( |
| 155 | + [1 if _classified_positive(sent) else 0 for sent in tot_sentiments] |
| 156 | + ) |
| 157 | + num_negative = sum( |
| 158 | + [1 if not _classified_positive(sent) else 0 for sent in tot_sentiments] |
| 159 | + ) |
| 160 | + print("\n\n\n") |
| 161 | + print("###########################################################################") |
| 162 | + print(f"Completed analyzing {len(tweets)} tweets for sentiment,") |
| 163 | + |
| 164 | + if num_positive >= num_negative: |
| 165 | + print( |
| 166 | + f"[green]General sentiment is positive with " |
| 167 | + f"{100*num_positive/float(len(tot_sentiments)):.0f}% in favor.[/green]" |
| 168 | + ) |
| 169 | + else: |
| 170 | + |
| 171 | + print( |
| 172 | + f"[magenta]General sentiment is negative with " |
| 173 | + f"{100*num_negative/float(len(tot_sentiments)):.0f}% against.[/magenta]" |
| 174 | + ) |
| 175 | + print("###########################################################################") |
| 176 | + |
| 177 | + |
| 178 | +if __name__ == "__main__": |
| 179 | + analyze_tweets_sentiment() |
0 commit comments