Abu1998 commited on
Commit
9b3cfd9
·
verified ·
1 Parent(s): 4bb349b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -53
app.py CHANGED
@@ -1,79 +1,93 @@
 
1
  import requests
2
  import csv
3
- import gradio as gr
4
- import os
5
 
6
- def fetch_comments(api_key, video_id):
7
- """
8
- Fetch comments from a YouTube video using the YouTube Data API.
9
 
10
- Parameters:
11
- - api_key: Google API key.
12
- - video_id: YouTube video ID.
 
 
 
 
 
 
 
13
 
14
- Returns:
15
- - Path to the CSV file containing commenters' usernames and IDs.
 
16
  """
17
- base_url = "https://www.googleapis.com/youtube/v3/commentThreads"
18
- params = {
19
- "part": "snippet",
20
- "videoId": video_id,
21
- "key": api_key,
22
- "maxResults": 100
23
- }
24
 
25
- response = requests.get(base_url, params=params)
26
- if response.status_code == 200:
 
 
 
 
 
27
  data = response.json()
28
- items = data.get("items", [])
29
 
30
- # Prepare CSV
31
- filename = "comments.csv"
32
- with open(filename, mode="w", newline="", encoding="utf-8") as file:
33
- writer = csv.writer(file)
34
- writer.writerow(["Username", "User ID", "Comment"])
35
-
36
- for item in items:
37
- snippet = item.get("snippet", {}).get("topLevelComment", {}).get("snippet", {})
38
- username = snippet.get("authorDisplayName", "N/A")
39
- user_id = snippet.get("authorChannelId", {}).get("value", "N/A")
40
- comment = snippet.get("textDisplay", "N/A")
41
- writer.writerow([username, user_id, comment])
42
-
43
- return filename
44
- else:
45
- return f"Error: {response.status_code} - {response.text}"
46
 
47
- def gradio_interface(api_key, video_id):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  """
49
- Gradio interface function to fetch comments and create a downloadable CSV.
50
  """
51
- csv_path = fetch_comments(api_key, video_id)
52
- if csv_path.startswith("Error"):
53
- return csv_path, None
54
- return "CSV file created successfully. Click the link to download.", csv_path
55
 
56
- # Gradio App
57
  with gr.Blocks() as demo:
58
- gr.Markdown("### YouTube Comment Exporter")
59
- gr.Markdown("Fetch usernames and user IDs of commenters on a YouTube video.")
60
-
61
  with gr.Row():
62
- api_key_input = gr.Textbox(label="API Key", placeholder="Enter your Google API key", type="password")
63
- video_id_input = gr.Textbox(label="Video ID", placeholder="Enter the YouTube video ID")
64
 
65
  with gr.Row():
66
- fetch_button = gr.Button("Fetch Comments")
67
 
68
  with gr.Row():
69
- message_output = gr.Textbox(label="Status", interactive=False)
70
  download_link = gr.File(label="Download CSV")
71
 
72
- fetch_button.click(
73
  fn=gradio_interface,
74
- inputs=[api_key_input, video_id_input],
75
  outputs=[message_output, download_link]
76
  )
77
 
78
- # Launch the App
79
  demo.launch()
 
1
+ import gradio as gr
2
  import requests
3
  import csv
4
+ import re
5
+ from datetime import timedelta
6
 
7
+ # YouTube API key and required endpoint
8
+ API_KEY = 'YOUR_YOUTUBE_API_KEY' # Replace with your API key
9
+ YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/videos'
10
 
11
+ def parse_duration(duration):
12
+ """
13
+ Parse ISO 8601 duration string to seconds.
14
+ Example: "PT1H10M5S" -> 4205 seconds
15
+ """
16
+ regex = re.match(r"PT(\d+H)?(\d+M)?(\d+S)?", duration)
17
+ hours = int(regex.group(1)[:-1] if regex.group(1) else 0)
18
+ minutes = int(regex.group(2)[:-1] if regex.group(2) else 0)
19
+ seconds = int(regex.group(3)[:-1] if regex.group(3) else 0)
20
+ return hours * 3600 + minutes * 60 + seconds
21
 
22
+ def fetch_video_data(video_ids):
23
+ """
24
+ Fetch video details (title, duration) from YouTube API.
25
  """
26
+ video_data = []
27
+ total_time_spent = 0 # Total time spent in seconds
 
 
 
 
 
28
 
29
+ for video_id in video_ids:
30
+ params = {
31
+ 'part': 'contentDetails,snippet',
32
+ 'id': video_id,
33
+ 'key': API_KEY
34
+ }
35
+ response = requests.get(YOUTUBE_API_URL, params=params)
36
  data = response.json()
 
37
 
38
+ if 'items' in data:
39
+ item = data['items'][0]
40
+ title = item['snippet']['title']
41
+ duration = item['contentDetails']['duration']
42
+ video_duration_seconds = parse_duration(duration)
43
+ total_time_spent += video_duration_seconds
 
 
 
 
 
 
 
 
 
 
44
 
45
+ video_data.append({
46
+ 'Video ID': video_id,
47
+ 'Title': title,
48
+ 'Duration (seconds)': video_duration_seconds
49
+ })
50
+
51
+ # Convert total time spent to hours and minutes
52
+ total_time_spent_in_hours = str(timedelta(seconds=total_time_spent))
53
+
54
+ # Save data to CSV
55
+ filename = "videos_time_spent.csv"
56
+ with open(filename, mode="w", newline="", encoding="utf-8") as file:
57
+ writer = csv.DictWriter(file, fieldnames=["Video ID", "Title", "Duration (seconds)"])
58
+ writer.writeheader()
59
+ writer.writerows(video_data)
60
+
61
+ return filename, total_time_spent_in_hours
62
+
63
+ def gradio_interface(video_ids):
64
  """
65
+ Gradio interface function to process video IDs and generate time statistics.
66
  """
67
+ video_ids_list = video_ids.split(",") # Convert input string to list
68
+ csv_file, total_time = fetch_video_data(video_ids_list)
69
+ return f"Total time spent: {total_time} on these videos. Download the CSV below.", csv_file
 
70
 
71
+ # Gradio App setup
72
  with gr.Blocks() as demo:
73
+ gr.Markdown("### Time Spent on YouTube Videos")
74
+ gr.Markdown("Enter a list of YouTube video IDs (comma separated) to calculate the time spent on each video.")
75
+
76
  with gr.Row():
77
+ video_ids_input = gr.Textbox(label="Enter Video IDs", placeholder="e.g., dQw4w9WgXcQ, kJQP7kiw5Fk")
 
78
 
79
  with gr.Row():
80
+ submit_button = gr.Button("Calculate Time Spent")
81
 
82
  with gr.Row():
83
+ message_output = gr.Textbox(label="Result", interactive=False)
84
  download_link = gr.File(label="Download CSV")
85
 
86
+ submit_button.click(
87
  fn=gradio_interface,
88
+ inputs=[video_ids_input],
89
  outputs=[message_output, download_link]
90
  )
91
 
92
+ # Launch the app
93
  demo.launch()