Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,24 +4,24 @@ import whisper
|
|
| 4 |
import tempfile
|
| 5 |
import gradio as gr
|
| 6 |
from pydub import AudioSegment
|
| 7 |
-
import fitz # PyMuPDF
|
| 8 |
-
import docx #
|
| 9 |
-
import pandas as pd #
|
| 10 |
-
# from google.colab import userdata #
|
| 11 |
import requests
|
| 12 |
from bs4 import BeautifulSoup
|
| 13 |
|
| 14 |
-
#
|
| 15 |
# openai.api_key = userdata.get('OPENAI_API_KEY')
|
| 16 |
|
| 17 |
-
#
|
| 18 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 19 |
|
| 20 |
-
#
|
| 21 |
model = whisper.load_model("large")
|
| 22 |
|
| 23 |
def preprocess_audio(audio_file):
|
| 24 |
-
"""
|
| 25 |
try:
|
| 26 |
audio = AudioSegment.from_file(audio_file)
|
| 27 |
audio = audio.apply_gain(-audio.dBFS + (-20))
|
|
@@ -29,150 +29,150 @@ def preprocess_audio(audio_file):
|
|
| 29 |
audio.export(temp_file.name, format="mp3")
|
| 30 |
return temp_file.name
|
| 31 |
except Exception as e:
|
| 32 |
-
return f"Error
|
| 33 |
|
| 34 |
-
def
|
| 35 |
-
"""Transcribe
|
| 36 |
try:
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
return
|
| 40 |
except Exception as e:
|
| 41 |
-
return f"Error
|
| 42 |
|
| 43 |
-
def
|
| 44 |
-
"""
|
| 45 |
try:
|
| 46 |
-
if
|
| 47 |
-
doc = fitz.open(
|
| 48 |
-
return "\n".join([
|
| 49 |
-
elif
|
| 50 |
-
doc = docx.Document(
|
| 51 |
-
return "\n".join([
|
| 52 |
-
elif
|
| 53 |
-
return pd.read_excel(
|
| 54 |
-
elif
|
| 55 |
-
return pd.read_csv(
|
| 56 |
else:
|
| 57 |
-
return "
|
| 58 |
except Exception as e:
|
| 59 |
-
return f"Error
|
| 60 |
|
| 61 |
-
def
|
| 62 |
-
"""
|
| 63 |
try:
|
| 64 |
response = requests.get(url)
|
| 65 |
response.raise_for_status()
|
| 66 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 67 |
return soup.get_text()
|
| 68 |
except Exception as e:
|
| 69 |
-
return f"Error
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
"""
|
| 73 |
-
|
| 74 |
-
num_audios = 5 * 3 # 5 audios * 3
|
| 75 |
audios = args[:num_audios]
|
| 76 |
-
|
| 77 |
|
| 78 |
for url in urls.split():
|
| 79 |
if url:
|
| 80 |
-
|
| 81 |
|
| 82 |
-
for
|
| 83 |
-
if
|
| 84 |
-
|
| 85 |
|
| 86 |
for i in range(0, len(audios), 3):
|
| 87 |
-
audio_file,
|
| 88 |
if audio_file is not None:
|
| 89 |
-
|
| 90 |
|
| 91 |
-
|
| 92 |
|
| 93 |
-
for idx, data in enumerate(
|
| 94 |
if data["audio"] is not None:
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
if
|
| 99 |
-
|
| 100 |
-
|
| 101 |
else:
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
-
|
| 111 |
-
-
|
| 112 |
-
-
|
| 113 |
-
-
|
| 114 |
-
-
|
| 115 |
-
-
|
| 116 |
-
-
|
| 117 |
"""
|
| 118 |
|
| 119 |
prompt = f"""
|
| 120 |
-
{
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
{
|
| 128 |
"""
|
| 129 |
|
| 130 |
try:
|
| 131 |
-
|
| 132 |
model="gpt-3.5-turbo",
|
| 133 |
messages=[{"role": "user", "content": prompt}],
|
| 134 |
temperature=0.1
|
| 135 |
)
|
| 136 |
-
|
| 137 |
-
return
|
| 138 |
except Exception as e:
|
| 139 |
-
return f"Error
|
| 140 |
|
| 141 |
with gr.Blocks() as demo:
|
| 142 |
-
gr.Markdown("##
|
| 143 |
with gr.Row():
|
| 144 |
with gr.Column(scale=2):
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
urls = gr.Textbox(label="URLs (
|
| 150 |
with gr.Column(scale=3):
|
| 151 |
-
inputs_list = [
|
| 152 |
with gr.Tabs():
|
| 153 |
for i in range(1, 6):
|
| 154 |
with gr.TabItem(f"Audio {i}"):
|
| 155 |
audio = gr.Audio(type="filepath", label=f"Audio {i}")
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
inputs_list.extend([audio,
|
| 159 |
for i in range(1, 6):
|
| 160 |
-
with gr.TabItem(f"
|
| 161 |
-
|
| 162 |
-
inputs_list.append(
|
| 163 |
|
| 164 |
-
gr.Markdown("---") #
|
| 165 |
|
| 166 |
with gr.Row():
|
| 167 |
-
|
| 168 |
|
| 169 |
-
gr.Markdown("---") #
|
| 170 |
|
| 171 |
with gr.Row():
|
| 172 |
-
|
| 173 |
with gr.Row():
|
| 174 |
-
|
| 175 |
|
| 176 |
-
|
| 177 |
|
| 178 |
-
demo.launch(share=True)
|
|
|
|
| 4 |
import tempfile
|
| 5 |
import gradio as gr
|
| 6 |
from pydub import AudioSegment
|
| 7 |
+
import fitz # PyMuPDF for handling PDFs
|
| 8 |
+
import docx # For handling .docx files
|
| 9 |
+
import pandas as pd # For handling .xlsx and .csv files
|
| 10 |
+
# from google.colab import userdata # Import userdata from google.colab
|
| 11 |
import requests
|
| 12 |
from bs4 import BeautifulSoup
|
| 13 |
|
| 14 |
+
# Configure your OpenAI API key using Google Colab userdata
|
| 15 |
# openai.api_key = userdata.get('OPENAI_API_KEY')
|
| 16 |
|
| 17 |
+
# Load environment variables from the Hugging Face environment
|
| 18 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 19 |
|
| 20 |
+
# Load the highest quality Whisper model once
|
| 21 |
model = whisper.load_model("large")
|
| 22 |
|
| 23 |
def preprocess_audio(audio_file):
|
| 24 |
+
"""Preprocess the audio file to improve quality."""
|
| 25 |
try:
|
| 26 |
audio = AudioSegment.from_file(audio_file)
|
| 27 |
audio = audio.apply_gain(-audio.dBFS + (-20))
|
|
|
|
| 29 |
audio.export(temp_file.name, format="mp3")
|
| 30 |
return temp_file.name
|
| 31 |
except Exception as e:
|
| 32 |
+
return f"Error preprocessing the audio file: {str(e)}"
|
| 33 |
|
| 34 |
+
def transcribe_audio(audio_file):
|
| 35 |
+
"""Transcribe an audio file."""
|
| 36 |
try:
|
| 37 |
+
file_path = preprocess_audio(audio_file) if isinstance(audio_file, str) else preprocess_audio(tempfile.NamedTemporaryFile(delete=False, suffix=".mp3", mode='w+b').name)
|
| 38 |
+
result = model.transcribe(file_path)
|
| 39 |
+
return result.get("text", "Error in transcription")
|
| 40 |
except Exception as e:
|
| 41 |
+
return f"Error processing the audio file: {str(e)}"
|
| 42 |
|
| 43 |
+
def read_document(document_path):
|
| 44 |
+
"""Read the content of a PDF, DOCX, XLSX or CSV document."""
|
| 45 |
try:
|
| 46 |
+
if document_path.endswith(".pdf"):
|
| 47 |
+
doc = fitz.open(document_path)
|
| 48 |
+
return "\n".join([page.get_text() for page in doc])
|
| 49 |
+
elif document_path.endswith(".docx"):
|
| 50 |
+
doc = docx.Document(document_path)
|
| 51 |
+
return "\n".join([paragraph.text for paragraph in doc.paragraphs])
|
| 52 |
+
elif document_path.endswith(".xlsx"):
|
| 53 |
+
return pd.read_excel(document_path).to_string()
|
| 54 |
+
elif document_path.endswith(".csv"):
|
| 55 |
+
return pd.read_csv(document_path).to_string()
|
| 56 |
else:
|
| 57 |
+
return "Unsupported file type. Please upload a PDF, DOCX, XLSX or CSV document."
|
| 58 |
except Exception as e:
|
| 59 |
+
return f"Error reading the document: {str(e)}"
|
| 60 |
|
| 61 |
+
def read_url(url):
|
| 62 |
+
"""Read the content of a URL."""
|
| 63 |
try:
|
| 64 |
response = requests.get(url)
|
| 65 |
response.raise_for_status()
|
| 66 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 67 |
return soup.get_text()
|
| 68 |
except Exception as e:
|
| 69 |
+
return f"Error reading the URL: {str(e)}"
|
| 70 |
|
| 71 |
+
def generate_news(instructions, facts, size, tone, urls, *args):
|
| 72 |
+
"""Generate a news article based on instructions, facts, URLs, documents, and transcriptions."""
|
| 73 |
+
knowledge_base = {"instructions": instructions, "facts": facts, "document_content": [], "audio_data": [], "url_content": []}
|
| 74 |
+
num_audios = 5 * 3 # 5 audios * 3 fields (audio, name, position)
|
| 75 |
audios = args[:num_audios]
|
| 76 |
+
documents = args[num_audios:]
|
| 77 |
|
| 78 |
for url in urls.split():
|
| 79 |
if url:
|
| 80 |
+
knowledge_base["url_content"].append(read_url(url))
|
| 81 |
|
| 82 |
+
for document in documents:
|
| 83 |
+
if document is not None:
|
| 84 |
+
knowledge_base["document_content"].append(read_document(document.name))
|
| 85 |
|
| 86 |
for i in range(0, len(audios), 3):
|
| 87 |
+
audio_file, name, position = audios[i:i+3]
|
| 88 |
if audio_file is not None:
|
| 89 |
+
knowledge_base["audio_data"].append({"audio": audio_file, "name": name, "position": position})
|
| 90 |
|
| 91 |
+
transcriptions_text, raw_transcriptions, total_direct_quotes = "", "", 0
|
| 92 |
|
| 93 |
+
for idx, data in enumerate(knowledge_base["audio_data"]):
|
| 94 |
if data["audio"] is not None:
|
| 95 |
+
transcription = transcribe_audio(data["audio"])
|
| 96 |
+
transcription_text = f'"{transcription}" - {data["name"]}, {data["position"]}'
|
| 97 |
+
raw_transcription = f'[Audio {idx + 1}]: "{transcription}" - {data["name"]}, {data["position"]}'
|
| 98 |
+
if total_direct_quotes < len(knowledge_base["audio_data"]) * 0.8:
|
| 99 |
+
transcriptions_text += transcription_text + "\n"
|
| 100 |
+
total_direct_quotes += 1
|
| 101 |
else:
|
| 102 |
+
transcriptions_text += f'{data["name"]} mentioned that {transcription}' + "\n"
|
| 103 |
+
raw_transcriptions += raw_transcription + "\n\n"
|
| 104 |
+
|
| 105 |
+
document_content = "\n\n".join(knowledge_base["document_content"])
|
| 106 |
+
url_content = "\n\n".join(knowledge_base["url_content"])
|
| 107 |
+
|
| 108 |
+
internal_prompt = """
|
| 109 |
+
Instructions for the model:
|
| 110 |
+
- Follow the principles of news writing: always try to answer the 5 Ws of a news story in the first paragraph (Who?, What?, When?, Where?, Why?).
|
| 111 |
+
- Ensure that at least 80% of the quotes are direct and in quotation marks.
|
| 112 |
+
- The remaining 20% can be indirect quotes.
|
| 113 |
+
- Do not invent new information.
|
| 114 |
+
- Be rigorous with the provided facts.
|
| 115 |
+
- When processing uploaded documents, extract and highlight important quotes and verbatim testimonies from sources.
|
| 116 |
+
- When processing uploaded documents, extract and highlight key figures.
|
| 117 |
"""
|
| 118 |
|
| 119 |
prompt = f"""
|
| 120 |
+
{internal_prompt}
|
| 121 |
+
Write a news article with the following information, including a title, a 15-word hook (additional information that complements the title), and the body content with a size of {size} words. The tone should be {tone}.
|
| 122 |
+
Instructions: {knowledge_base["instructions"]}
|
| 123 |
+
Facts: {knowledge_base["facts"]}
|
| 124 |
+
Additional content from documents: {document_content}
|
| 125 |
+
Additional content from URLs: {url_content}
|
| 126 |
+
Use the following transcriptions as direct and indirect quotes (without changing or inventing content):
|
| 127 |
+
{transcriptions_text}
|
| 128 |
"""
|
| 129 |
|
| 130 |
try:
|
| 131 |
+
response = openai.ChatCompletion.create(
|
| 132 |
model="gpt-3.5-turbo",
|
| 133 |
messages=[{"role": "user", "content": prompt}],
|
| 134 |
temperature=0.1
|
| 135 |
)
|
| 136 |
+
news_article = response['choices'][0]['message']['content']
|
| 137 |
+
return news_article, raw_transcriptions
|
| 138 |
except Exception as e:
|
| 139 |
+
return f"Error generating the news article: {str(e)}", ""
|
| 140 |
|
| 141 |
with gr.Blocks() as demo:
|
| 142 |
+
gr.Markdown("## All-in-One News Generator")
|
| 143 |
with gr.Row():
|
| 144 |
with gr.Column(scale=2):
|
| 145 |
+
instructions = gr.Textbox(label="Instructions for the news article", lines=2)
|
| 146 |
+
facts = gr.Textbox(label="Describe the facts of the news", lines=4)
|
| 147 |
+
size = gr.Number(label="Size of the news body (in words)", value=100)
|
| 148 |
+
tone = gr.Dropdown(label="Tone of the news", choices=["serious", "neutral", "lighthearted"], value="neutral")
|
| 149 |
+
urls = gr.Textbox(label="URLs (separated by space)", lines=2)
|
| 150 |
with gr.Column(scale=3):
|
| 151 |
+
inputs_list = [instructions, facts, size, tone, urls]
|
| 152 |
with gr.Tabs():
|
| 153 |
for i in range(1, 6):
|
| 154 |
with gr.TabItem(f"Audio {i}"):
|
| 155 |
audio = gr.Audio(type="filepath", label=f"Audio {i}")
|
| 156 |
+
name = gr.Textbox(label="Name", scale=1)
|
| 157 |
+
position = gr.Textbox(label="Position", scale=1)
|
| 158 |
+
inputs_list.extend([audio, name, position])
|
| 159 |
for i in range(1, 6):
|
| 160 |
+
with gr.TabItem(f"Document {i}"):
|
| 161 |
+
document = gr.File(label=f"Document {i}", type="filepath", file_count="single")
|
| 162 |
+
inputs_list.append(document)
|
| 163 |
|
| 164 |
+
gr.Markdown("---") # Visual separator
|
| 165 |
|
| 166 |
with gr.Row():
|
| 167 |
+
transcriptions_output = gr.Textbox(label="Transcriptions", lines=10)
|
| 168 |
|
| 169 |
+
gr.Markdown("---") # Visual separator
|
| 170 |
|
| 171 |
with gr.Row():
|
| 172 |
+
generate = gr.Button("Generate draft")
|
| 173 |
with gr.Row():
|
| 174 |
+
news_output = gr.Textbox(label="Generated draft", lines=20)
|
| 175 |
|
| 176 |
+
generate.click(fn=generate_news, inputs=inputs_list, outputs=[news_output, transcriptions_output])
|
| 177 |
|
| 178 |
+
demo.launch(share=True)
|