Kumarkishalaya commited on
Commit
3b36c24
·
verified ·
1 Parent(s): a592a3b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from googleapiclient.discovery import build
4
+ from selenium import webdriver
5
+ from selenium.webdriver.chrome.service import Service
6
+ from selenium.webdriver.chrome.options import Options
7
+ import openai
8
+ import gradio as gr
9
+ import time
10
+
11
+ # Set up the YouTube Data API key
12
+ YOUTUBE_API_KEY = 'AIzaSyB18WjBnkOYmTO3xiWlRqcVgwMAlPtLE0w'
13
+
14
+ def extract_video_id(url):
15
+ if "youtu.be" in url: # Mobile YouTube URL
16
+ return get_redirected_url_video_id(url)
17
+ else: # Desktop YouTube URL
18
+ video_id = re.search(r"v=([^&]+)", url).group(1)
19
+ return video_id
20
+
21
+ def get_redirected_url_video_id(mobile_url):
22
+ # Set up Chrome options to run headless (without opening a visible browser window)
23
+ chrome_options = Options()
24
+ chrome_options.add_argument("--headless")
25
+ chrome_options.add_argument("--disable-gpu")
26
+
27
+ # Specify the path to the ChromeDriver executable
28
+ chrome_driver_path = '/path/to/chromedriver' # Update this path
29
+
30
+ # Create a new Chrome session
31
+ service = Service(chrome_driver_path)
32
+ driver = webdriver.Chrome(service=service, options=chrome_options)
33
+
34
+ # Open the mobile YouTube link
35
+ driver.get(mobile_url)
36
+
37
+ # Wait for a few seconds to ensure the page has loaded
38
+ time.sleep(1)
39
+
40
+ # Get the current URL (which should be the full YouTube URL)
41
+ current_url = driver.current_url
42
+
43
+ # Close the browser
44
+ driver.quit()
45
+
46
+ # Extract the video ID from the current URL
47
+ video_id = re.search(r"v=([^&]+)", current_url).group(1)
48
+ return video_id
49
+
50
+
51
+ def get_youtube_comments(video_id):
52
+ youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
53
+ comments = []
54
+ try:
55
+ # Request to get comments
56
+ request = youtube.commentThreads().list(
57
+ part="snippet",
58
+ videoId=video_id,
59
+ maxResults=200
60
+ )
61
+ response = request.execute()
62
+
63
+ # Extract comments
64
+ for item in response['items']:
65
+ comment_data = item['snippet']['topLevelComment']['snippet']
66
+ comments.append({
67
+ 'text': comment_data['textOriginal'],
68
+ 'like_count': comment_data['likeCount']
69
+ })
70
+
71
+ while 'nextPageToken' in response and len(comments) < 1000:
72
+ request = youtube.commentThreads().list(
73
+ part="snippet",
74
+ videoId=video_id,
75
+ pageToken=response['nextPageToken'],
76
+ maxResults=100
77
+ )
78
+ response = request.execute()
79
+ for item in response['items']:
80
+ comment_data = item['snippet']['topLevelComment']['snippet']
81
+ comments.append({
82
+ 'text': comment_data['textOriginal'],
83
+ 'like_count': comment_data['likeCount']
84
+ })
85
+ if len(comments) >= 1000:
86
+ break
87
+ except Exception as e:
88
+ print(f"An error occurred: {e}")
89
+
90
+ # Sort comments by like count in descending order and take the top 20
91
+ comments = sorted(comments, key=lambda x: x['like_count'], reverse=True)[:20]
92
+ return [comment['text'] for comment in comments]
93
+
94
+
95
+ def generate_story(comments, temperature=0.7):
96
+ words = []
97
+ word_count = 0
98
+
99
+ for comment in comments:
100
+ comment_words = comment.split()
101
+ if word_count + len(comment_words) > 1000:
102
+ break
103
+ words.extend(comment_words)
104
+ word_count += len(comment_words)
105
+
106
+ comments_text = " ".join(words)
107
+ client = openai
108
+ completion = client.ChatCompletion.create(
109
+ model="gpt-3.5-turbo",
110
+ messages=[{"role": "system", "content": f"""
111
+
112
+ Read all the comments, understand the emotions people are feeling and pick any random emotion
113
+ and create a story in first person (the person can be randomly young or old and the story can be
114
+ based in past or future) based on that emotion picking a random character keep the words
115
+ simple and a bit profound but overall simple words. Give more weight to the comments that
116
+ come earlier in sequence. The comments are given here: {comments_text}"""},
117
+ {"role": "user", "content": """
118
+ ignore the comment which has lyrics of the song,
119
+ ignore all comments similar to 'anyone in 2024', Keep the story randomly between 50-120 words.
120
+ don't mention the emotion chosen just start the story.
121
+ sometimes include bits where you tell how this song makes you feel. be very nostalgic about a feeling or a place this
122
+ takes you to. half the times end the story with a hopeful future or a dark end or humorous.. choose randomly"""}]
123
+ ,temperature=temperature)
124
+ return completion.choices[0].message.content
125
+
126
+
127
+ # Main function to execute the process
128
+ def main(youtube_url, temperature):
129
+ video_id = extract_video_id(youtube_url)
130
+ comments = get_youtube_comments(video_id)
131
+ story = generate_story(comments, temperature)
132
+ return story
133
+
134
+
135
+ # Create Gradio interface
136
+ youtube_url_input = gr.Textbox(label="YouTube URL")
137
+ temperature_input = gr.Slider(minimum=0.0, maximum=2.0, value=0.7, label="Temperature (creativity)")
138
+
139
+ iface = gr.Interface(
140
+ fn=main,
141
+ inputs=[youtube_url_input, temperature_input],
142
+ outputs="text",
143
+ title="Let's hear a Story",
144
+ description="Enter a YouTube video URL to read a story which will capture the emotions of thousands of people before you who have listened to this and left comments :). The stories are AI-generated but does that mean it has never happened before or never will? Maybe the reader finds their own story with AI"
145
+ )
146
+
147
+ # Launch the interface
148
+ iface.launch()