File size: 3,919 Bytes
f191e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from tqdm import tqdm
from itertools import islice
from youtube_comment_downloader import *
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline

import matplotlib.pyplot as plt
import csv
import streamlit as st
import pandas as pd
import base64

 
# Inisialisasi model dan tokenizer
pretrained= "mdhugol/indonesia-bert-sentiment-classification"
model = AutoModelForSequenceClassification.from_pretrained(pretrained)
tokenizer = AutoTokenizer.from_pretrained(pretrained)
sentiment_analysis = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
label_index = {'LABEL_0': 'positive', 'LABEL_1': 'neutral', 'LABEL_2': 'negative'}

st.title("Youtube Comment Sentimen Analisis")

# Input URL video
video_url = st.text_input("Masukkan URL video YouTube:")

# Input jumlah komentar yang ingin diambil
num_comments = st.number_input("Jumlah komentar yang ingin diambil:", min_value=1, value=10)

# Fungsi untuk analisis sentimen
def analisis_sentimen(text):
    result = sentiment_analysis(text)
    label = label_index[result[0]['label']]
    score = result[0]['score'] * 100
    return label, score

if st.button("Mulai Analisis"):
    # Inisialisasi YoutubeCommentDownloader
    downloader = YoutubeCommentDownloader()

    # Mendapatkan komentar
    comments = downloader.get_comments_from_url(video_url, sort_by=SORT_BY_POPULAR)

    # Membuka file CSV untuk menulis
    with open('comments.csv', mode='w', encoding='utf-8', newline='') as file:
        # Membuat objek writer
        writer = csv.DictWriter(file, fieldnames=['cid', 'text', 'time', 'author', 'channel', 'votes', 'photo', 'heart', 'reply'])
        
        # Menulis header
        writer.writeheader()
        
        # Menulis data komentar
        for comment in tqdm(islice(comments, num_comments)):
            # Menghapus kolom 'time_parsed' dari komentar
            comment.pop('time_parsed', None)
            writer.writerow(comment)

    st.success(f"Komentar berhasil diunduh dan disimpan dalam file 'comments.csv'")
    
    # Membaca data dari file CSV
    comments_df = pd.read_csv('comments.csv')
    
    #analisis sentimen
    st.info("Memulai analisis sentimen....")

    # List untuk menyimpan hasil analisis sentimen
    hasil_analisis = []

    # Membaca data dari file CSV
    with open('comments.csv', mode='r', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        for row in tqdm(reader):
            comment_text = row['text']
            label, score = analisis_sentimen(comment_text)
            hasil_analisis.append((comment_text, label, score))

    # Menampilkan hasil analisis sentimen
    st.subheader("Hasil Analisis Sentimen")
    #st.write(hasil_analisis)

    # Menampilkan histogram
    labels, scores = zip(*[(label, score) for _, label, score in hasil_analisis])
    plt.hist(labels, bins=30, color='blue', alpha=0.7, edgecolor='black')
    plt.xlabel('Skor Sentimen')
    plt.ylabel('Jumlah Komentar')
    plt.title('Distribusi Sentimen Komentar')
    st.pyplot(plt)

    # Menghitung jumlah dan persentase
    jumlah_positif = labels.count('positive')
    jumlah_negatif = labels.count('negative')
    jumlah_netral = labels.count('neutral')
    total_komentar = len(labels)
    persentase_positif = (jumlah_positif / total_komentar) * 100
    persentase_negatif = (jumlah_negatif / total_komentar) * 100
    persentase_netral = (jumlah_netral / total_komentar) * 100

    st.write(f"Total Komentar: {total_komentar}")
    st.write(f"Persentase Komentar Positif: {persentase_positif:.2f}% / {jumlah_positif} Komentar")
    st.write(f"Persentase Komentar Negatif: {persentase_negatif:.2f}% / {jumlah_negatif} Komentar")
    st.write(f"Persentase Komentar Netral: {persentase_netral:.2f}% / {jumlah_netral} Komentar")
    
    # Menampilkan tabel dengan menggunakan st.table()
    st.subheader("Data Komentar")
    st.table(comments_df)