EduArticles / app.py
Hokeno's picture
Rename app2.py to app.py
91473d5 verified
import os
import gradio as gr
from groq import Groq
from datetime import datetime
import requests
output_dir = "./outputs"
os.makedirs(output_dir, exist_ok=True)
groq_client = Groq(api_key=os.getenv('GROQ_API_KEY'))
PEXELS_API_KEY = os.getenv('PEXELS_API_KEY')
def translate_prompt(prompt, language):
if language == "Indonesian":
translation_prompt = (
f"Terjemahkan teks berikut ke dalam bahasa Inggris secara singkat dan akurat, cocok untuk pencarian video: {prompt}"
)
completion = groq_client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": translation_prompt}],
temperature=0.5,
max_tokens=8192,
stream=False
)
return completion.choices[0].message.content.strip()
return prompt
def fetch_pexels_video(query):
headers = {"Authorization": PEXELS_API_KEY}
url = f"https://api.pexels.com/videos/search?query={query}&per_page=1"
response = requests.get(url, headers=headers)
if response.status_code == 200:
videos = response.json().get("videos", [])
if videos and videos[0]["video_files"]:
return videos[0]["video_files"][0]["link"]
return None
def save_video(video_url, output_path):
if not video_url:
return None
response = requests.get(video_url)
if response.status_code == 200:
with open(output_path, "wb") as f:
f.write(response.content)
return output_path
return None
def generate_script(topic, language):
if language == "Indonesian":
enhanced_prompt = (
f"Tulis artikel edukasi singkat dalam bahasa Indonesia tentang topik: {topic}. "
"Artikel harus informatif, terstruktur, dan mudah dipahami dengan: "
"1) pendahuluan yang memperkenalkan topik, "
"2) fakta utama atau konsep penting tentang topik, "
"3) contoh atau konteks nyata untuk memperjelas, "
"4) penutup yang mendorong pembelajaran lebih lanjut. "
"Gunakan bahasa yang jelas, formal, dan menarik untuk artikel edukasi."
)
else:
enhanced_prompt = (
f"Write a short educational article in English about the topic: {topic}. "
"The article should be informative, structured, and easy to understand with: "
"1) an introduction introducing the topic, "
"2) key facts or core concepts about the topic, "
"3) a real-world example or context to clarify, "
"4) a conclusion encouraging further learning. "
"Use clear, formal, and engaging language suitable for an educational article."
)
completion = groq_client.chat.completions.create(
model="meta-llama/llama-4-scout-17b-16e-instruct",
messages=[{"role": "user", "content": enhanced_prompt}],
temperature=0.7,
max_tokens=8192,
stream=False
)
return completion.choices[0].message.content.strip()
def save_outputs(script, topic, language):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
script_filename = os.path.join(output_dir, f"script_{language.lower()}_{timestamp}.txt")
video_filename = os.path.join(output_dir, f"video_{language.lower()}_{timestamp}.mp4")
with open(script_filename, "w", encoding="utf-8") as f:
f.write(f"Topik: {topic}\nBahasa: {language}\n\n{script}")
video_query = translate_prompt(topic, language)
video_url = fetch_pexels_video(video_query)
video_path = save_video(video_url, video_filename) if video_url else None
video_status = f"Video disimpan sebagai {video_filename}" if video_path else "Tidak ada video yang ditemukan untuk topik ini."
return script_filename, video_status, video_path
def generate_content(topic, language):
if not topic:
return "Masukkan topik edukasi.", None, None, None
script = generate_script(topic, language)
script_filename, video_status, video_path = save_outputs(script, topic, language)
return script, script_filename, video_status, video_path
interface = gr.Interface(
fn=generate_content,
inputs=[
gr.Textbox(lines=2, placeholder="Enter the story promt here..."),
gr.Dropdown(choices=["Indonesian", "English"], label="Select Language", value="English")
],
outputs=[
gr.Textbox(label="Generated Article"),
gr.Textbox(label="The Article has been saved"),
gr.Textbox(label="The video has been saved"),
gr.Video(label="Generated Video")
],
examples=[
["Sejarah candi Borobudur", "Indonesian"],
["The basics of photosynthesis", "English"]
]
)
# Launch interface
interface.launch()