in nlp-sentiment-analysis/code/main.py [0:0]
def process_document(bucket_name, object_name):
"""Performs sentiment analysis on a text document stored in GCS."""
print("Document processing started.")
language_client = language_v2.LanguageServiceClient()
storage_client = storage.Client()
file_path = f"/tmp/{object_name}"
print(f"Downloading document to: {file_path}")
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(object_name)
blob.download_to_filename(file_path)
with open(file_path, "r") as text_file:
document_content = text_file.read()
print("Performing sentiment analysis...")
document = language_v2.Document(content=document_content, type_=language_v2.Document.Type.PLAIN_TEXT)
response = language_client.analyze_sentiment(request={"document": document})
# Get results
sentiment_score = response.document_sentiment.score
sentiment_magnitude = response.document_sentiment.magnitude
sentences = [
{"text": sentence.text.content, "sentiment": sentence.sentiment.score}
for sentence in response.sentences
]
process_output(
bucket_name,
object_name,
sentiment_score,
sentiment_magnitude,
sentences,
)