File size: 7,580 Bytes
97ed0ae
 
 
 
 
 
 
 
 
 
 
 
 
3d60d11
97ed0ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6201c6d
97ed0ae
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import csv
import pytube
from pytube import YouTube
import moviepy.editor as mp
from pydub import AudioSegment
from urllib.parse import urlparse
import os
import whisper
import openai
import json
import ffmpeg
import yt_dlp

model = whisper.load_model("large")

def Analyze(video_link):

    video_url = f"{video_link}"

    # Your existing code for processing the video and analyzing with ChatGPT

    # Extracting details of the Video
    print("Extracting Video Details"'\n')
    try:
        video = YouTube(video_url)
        video_channel = video.author
        video_title = video.title
        video_description = video.description
        video_url = video.watch_url

        print(f"Channel Name: {video_channel}")
        print(f"Video Tile: {video_title}")
        print(f"Video URL: {video_url}")
        print(f"Video Description: {video_description}")
    except Exception as e:
        print(f"An error occured: {str(e)}")

    #---        
    try:
        # Determine if it's for YouTube or YouTube Shorts and save the audio \
        # file according to its video ID
        parsed_url = urlparse(video_url)
        if 'youtube.com' in parsed_url.netloc:
            if '/shorts/' in parsed_url.path:
                # It's a YouTube Shorts URL
                video_id = parsed_url.path.split('/shorts/')[-1]
            else:
                # It's a regular YouTube video URL
                query_params = parsed_url.query.split('&')
                video_id = None
                for param in query_params:
                    if param.startswith('v='):
                        video_id = param[2:]
                        break
                if video_id is None:
                    print("Invalid YouTube video URL. No video ID found.")
        else:
            print("Invalid URL. Please provide a valid YouTube URL.")
    
        #---
    
        # Downloading audio and converting to .wav format
        print("Downloading Audio")
        if video_id:
            # Replace 'VIDEO_URL' with the actual URL of the video you want to download
    
            # Options to download only audio in the best quality available
            options = {
                'format': 'bestaudio/best',
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': 'best',
                }],
                'outtmpl': '%(id)s.%(ext)s',
                'quiet': True,  # Set quiet to True to suppress verbose output
            }
    
            # Create yt-dlp object with specified options
            ydl = yt_dlp.YoutubeDL(options)
    
            # Download the video
            ydl.download([video_url])
            print("AUDIO DOWNLOADED")
            savepath_audio = f'{video_id}.mp3'
    
        print(savepath_audio)
        print('\n'"Audio path: ", savepath_audio)
        #Whisper Transcription
        print('\n'"Transcribing Audio, Please wait!"'\n')
        result = model.transcribe(savepath_audio, verbose=True, task='translate')
        os.remove(savepath_audio)
    
        combined_data = ""
    
        for segment in result['segments']:
            start_time = "[{:02d}:{:06.3f}".format(int(segment['start']) // 60, segment['start'] % 60)
            end_time = "{:02d}:{:06.3f}]".format(int(segment['end']) // 60, segment['end'] % 60)
            timestamp = start_time + ' --> ' + end_time
            text = segment['text']
    
            # Combining transcript into a single string with newlines
            combined_data += timestamp + ' ' + text + '\n'
    
        #----
    
        #Using ChatGPT for Analysis
        openai.api_key = os.environ.get('API_KEY')
    
    
        def callChatGPT(input_text):
    
    
            #input_prompt = "I have receive the message following message: " + '"' + str(input_text)  + '"'  + "."
            input_prompt = """you will be provided a transcript of a video with timestamp. perform the following actions keeping \
                youtube commmunity guidelines, giving importance to freedom of speech and differentiating between fact and opinion,\
                and the idea that people are free to believe what they want to believe and say what they want about other people with\
                different viewpoints \
                (as long as the latter do not belong to 'protected group' category i.e., video should not hateful towards age, caste, \
                disability, ethnicity, gender identity and expression, nationality, race, immigration status, religion,\
                sex/gender, sexual orientation, victims of a major violent event and their kin, and veteran status; if it is not \
                against any protected group, then \
                flag ONLY if the language is extremely hateful - ignore minor everyday foul deragatory language) in mind:
                1 - summarize the text delimited by triple backticks with 1-2 sentence \
                2 - provide the overall sentiment of the text \
                3 - differentiate between fact or opinion - if it is an opinion, flag the text as not hateful by default unless there are explicit/hateful words \
                4 - check for any hate in the text. if it does then just say yes else say no \
                5 - if the text contains hate then mention all the timestamps and it's texts where it contains hate \
                6 - classify the risk/degree of hate into high, medium, or low \
                7 - if flagged as hate, explain why
                8 - output a json object which contains the following keys: \
                summary, sentiment, presence_of_hate, hate_degree, part_which_contains_hate, fact_or_opinion, explanation""" + '```' + str(input_text)  + '```'  + "."
    
    
            response = openai.ChatCompletion.create(
              model="gpt-3.5-turbo",
              messages=[
                    {"role": "user", "content": input_prompt}
                ],
              temperature=0,
            )
    
            return response
    
        input_text = (f"""{combined_data}""")
        print('\n'"ANALYZING..."'\n')
        response_AI = callChatGPT(input_text)
    
        # Extracting values from the response
        response_data = response_AI['choices'][0]['message']['content']
        response_json = json.loads(response_data)
        summary = response_json.get('summary', '')
        sentiment = response_json.get('sentiment', '')
        presence_of_hate = response_json.get('presence_of_hate', '')
        hate_degree = response_json.get('hate_degree', '')
        part_which_contains_hate = response_json.get('part_which_contains_hate', '')
        foo = response_json.get('fact_or_opinion', '')
        exp = response_json.get('explanation', '')
        
        print(text)
        print('\n')
        print("Summary:", summary)
        print("Sentiment:", sentiment)
        print("Fact or opinion: ", foo)
        print("Presence of Hate:", presence_of_hate)
        print("Explanation:", exp)
        print("Hate Degree:", hate_degree)
        print("Part Which Contains Hate:", part_which_contains_hate)
        
        return {'title': video_title, 'url': video_url, 'len': video.length, 'lang': result['language'], 'summary': summary, 'sentiment': sentiment, 'foo': foo, 'hate': presence_of_hate, 'explanation': exp, 'degree': hate_degree, 'part': part_which_contains_hate, 'transcript': input_text}
    except Exception as e:
        print(f"An error occured: Unable to process")