Repository navigation
Expand file tree
/
Copy pathupload_text.py
More file actions
84 lines (65 loc) · 2.64 KB
/
Copy pathupload_text.py
File metadata and controls
84 lines (65 loc) · 2.64 KB
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
import os
import fitz
from docx import Document
import mammoth
import requests
from bs4 import BeautifulSoup
from youtube_transcript_api import YouTubeTranscriptApi
import re
def extract_text(file_path: str) -> str:
ext = os.path.splitext(file_path)[1].lower()
# ---- PDF ----
if ext == ".pdf":
text = ""
with fitz.open(file_path) as pdf:
for page in pdf:
text += page.get_text()
return text
# ---- DOCX ----
elif ext == ".docx":
doc = Document(file_path)
return "\n".join([p.text for p in doc.paragraphs])
# ---- DOC (use Mammoth to convert to DOCX-like text) ----
elif ext == ".doc":
with open(file_path, "rb") as f:
result = mammoth.extract_raw_text(f)
return result.value
# ---- Plain text formats ----
elif ext in [".txt", ".md", ".csv", ".log"]:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
else:
raise ValueError(f"Unsupported file type: {ext}")
def extract_text_from_url(url: str) -> str:
try:
# Send GET request to the URL
response = requests.get(url, timeout=10)
response.raise_for_status()
# Parse HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get text
text = soup.get_text()
# Clean up text - remove extra whitespace
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
return text
except requests.exceptions.RequestException as e:
raise ValueError(f"Error fetching URL: {str(e)}")
except Exception as e:
raise ValueError(f"Error extracting text from URL: {str(e)}")
def extract_youtube_transcript(url: str) -> str:
try:
video_id_match = re.search(r'(?:v=|\/)([0-9A-Za-z_-]{11}).*', url)
if not video_id_match:
raise ValueError("Invalid YouTube URL")
video_id = video_id_match.group(1)
api = YouTubeTranscriptApi()
transcript_list = api.fetch(video_id)
transcript_text = ' '.join([entry.text for entry in transcript_list])
return transcript_text
except Exception as e:
raise ValueError(f"Error extracting YouTube transcript: {str(e)}")