WildVoices / app.py
neovalle's picture
Update app.py
8c40bcd verified
raw
history blame
5.02 kB
import gradio as gr
import requests
import os
import random
import pandas as pd
# Load instructions from local files
def load_instruction(persona):
try:
with open(f"instructions/{persona.lower()}.txt", "r") as file:
return file.read()
except FileNotFoundError:
return ""
# Call Cohere API
def call_cohere_api(system_instruction, user_prompt):
headers = {
"Authorization": f"Bearer {os.getenv('COHERE_API_KEY')}",
"Content-Type": "application/json"
}
# Append word limit instruction
user_prompt += "\n\nAnswer in 100 words or fewer."
payload = {
"model": "command-r-plus",
"message": user_prompt,
"preamble": system_instruction,
"max_tokens": 300
}
response = requests.post("https://api.cohere.ai/v1/chat", headers=headers, json=payload)
return response.json().get("text", "No response").strip()
# Load questions from file
def load_questions():
try:
with open("questions.txt", "r") as file:
return [line.strip() for line in file if line.strip()]
except FileNotFoundError:
return []
questions_list = load_questions()
# Generate random question
def get_random_question():
return random.choice(questions_list) if questions_list else "No questions available."
# Load counter-narratives CSV
def load_counternarratives():
try:
df = pd.read_csv("counternarratives.csv")
return df
except FileNotFoundError:
print("counternarratives.csv not found.")
return pd.DataFrame(columns=["myth", "fact", "persona"])
counternarratives = load_counternarratives()
# Generate Random Myth or Fact and trigger persona response
def get_random_myth_or_fact():
if counternarratives.empty:
return "No myths or facts available.", "Fact-Checker", "", "", ""
# πŸ”„ Randomly select a row from the dataframe
row = counternarratives.sample(1).iloc[0]
selected_column = random.choice(["myth", "fact"])
myth_or_fact = row[selected_column]
persona = row["persona"]
# πŸ”„ Call the Cohere API to get the persona's response
persona_instruction = load_instruction(persona)
persona_response = call_cohere_api(persona_instruction, myth_or_fact)
# βœ… Fact-checker response logic
if selected_column == "myth":
fact_check_response = f"πŸ›‘ **MYTH**\n\nThe fact is: {row['fact']}"
else:
fact_check_response = f"βœ… **FACT**\n\nIndeed, {row['fact']}"
# Return the myth/fact, update the personas, and fill the responses
return myth_or_fact, persona, persona_response, fact_check_response, f"### {persona} Responds","### Fact Checker"
# Dynamically load persona names from instructions folder
personas = [os.path.splitext(f)[0].capitalize() for f in os.listdir("instructions") if f.endswith(".txt")]
# Gradio Interface
with gr.Blocks() as demo:
with gr.Row():
with gr.Column(scale=0.15):
gr.Image(value="data/WildVoices.png", label="Wild Voices", show_label=False)
with gr.Column():
gr.Markdown("""
# 🌲 **Wild Voices**
*Listening to the More-than-Human World*
Ask questions to rivers, trees, owls, and more. Generate myths and facts, and let nature's wisdom respond.
You can also generate random questions or myth/fact prompts.
""")
with gr.Row():
persona1 = gr.Dropdown(personas, label="Choose First Persona", value="Earth")
persona2 = gr.Dropdown(personas, label="Choose Second Persona", value="Crow")
with gr.Row():
with gr.Column():
user_input = gr.Textbox(label="🌱 Your Question", placeholder="e.g., What do you think of humans?", lines=2)
with gr.Column(scale=0.15):
random_button = gr.Button("🎲 Generate Random Question")
myth_fact_button = gr.Button("πŸ€” Generate Random Myth/Fact")
with gr.Row():
ask_button = gr.Button("🌎 Submit Question")
with gr.Row():
with gr.Column(scale=0.50):
output1_title = gr.Markdown("### Persona1 Responds")
with gr.Column(scale=0.50):
output2_title = gr.Markdown("### Persona2 Responds")
with gr.Row():
output1 = gr.Textbox(label="")
output2 = gr.Textbox(label="")
# Button events
random_button.click(fn=get_random_question, inputs=[], outputs=[user_input])
# Myth/Fact button click event
myth_fact_button.click(
fn=get_random_myth_or_fact,
inputs=[],
outputs=[user_input, persona1, output1, output2, output1_title, output2_title]
)
# Ask button for normal questions
ask_button.click(
fn=lambda p1, p2, q: (call_cohere_api(load_instruction(p1), q),
call_cohere_api(load_instruction(p2), q)),
inputs=[persona1, persona2, user_input],
outputs=[output1, output2]
)
if __name__ == "__main__":
demo.launch()