Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,121 +1,124 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import requests
|
3 |
-
import os
|
4 |
-
import random
|
5 |
-
import pandas as pd
|
6 |
-
|
7 |
-
# Load instructions from local files
|
8 |
-
def load_instruction(persona):
|
9 |
-
try:
|
10 |
-
with open(f"instructions/{persona.lower()}.txt", "r") as file:
|
11 |
-
return file.read()
|
12 |
-
except FileNotFoundError:
|
13 |
-
return ""
|
14 |
-
|
15 |
-
# Call Cohere API
|
16 |
-
def call_cohere_api(system_instruction, user_prompt):
|
17 |
-
headers = {
|
18 |
-
"Authorization": f"Bearer {os.getenv('COHERE_API_KEY')}",
|
19 |
-
"Content-Type": "application/json"
|
20 |
-
}
|
21 |
-
|
22 |
-
# Append word limit instruction
|
23 |
-
user_prompt += "\n\nAnswer in 100 words or fewer."
|
24 |
-
payload = {
|
25 |
-
"model": "command-r-plus",
|
26 |
-
"message": user_prompt,
|
27 |
-
"preamble": system_instruction,
|
28 |
-
"max_tokens": 300
|
29 |
-
}
|
30 |
-
response = requests.post("https://api.cohere.ai/v1/chat", headers=headers, json=payload)
|
31 |
-
return response.json().get("text", "No response").strip()
|
32 |
-
|
33 |
-
# Load questions from file
|
34 |
-
def load_questions():
|
35 |
-
try:
|
36 |
-
with open("questions.txt", "r") as file:
|
37 |
-
return [line.strip() for line in file if line.strip()]
|
38 |
-
except FileNotFoundError:
|
39 |
-
return []
|
40 |
-
|
41 |
-
questions_list = load_questions()
|
42 |
-
|
43 |
-
# Generate random question
|
44 |
-
def get_random_question():
|
45 |
-
return random.choice(questions_list) if questions_list else "No questions available."
|
46 |
-
|
47 |
-
# Load counter-narratives CSV
|
48 |
-
def load_counternarratives():
|
49 |
-
try:
|
50 |
-
df = pd.read_csv("counternarratives.csv")
|
51 |
-
return df
|
52 |
-
except FileNotFoundError:
|
53 |
-
print("counternarratives.csv not found.")
|
54 |
-
return pd.DataFrame(columns=["myth", "fact", "persona"])
|
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 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
with gr.Row():
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
#
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import os
|
4 |
+
import random
|
5 |
+
import pandas as pd
|
6 |
+
|
7 |
+
# Load instructions from local files
|
8 |
+
def load_instruction(persona):
|
9 |
+
try:
|
10 |
+
with open(f"instructions/{persona.lower()}.txt", "r") as file:
|
11 |
+
return file.read()
|
12 |
+
except FileNotFoundError:
|
13 |
+
return ""
|
14 |
+
|
15 |
+
# Call Cohere API
|
16 |
+
def call_cohere_api(system_instruction, user_prompt):
|
17 |
+
headers = {
|
18 |
+
"Authorization": f"Bearer {os.getenv('COHERE_API_KEY')}",
|
19 |
+
"Content-Type": "application/json"
|
20 |
+
}
|
21 |
+
|
22 |
+
# Append word limit instruction
|
23 |
+
user_prompt += "\n\nAnswer in 100 words or fewer."
|
24 |
+
payload = {
|
25 |
+
"model": "command-r-plus",
|
26 |
+
"message": user_prompt,
|
27 |
+
"preamble": system_instruction,
|
28 |
+
"max_tokens": 300
|
29 |
+
}
|
30 |
+
response = requests.post("https://api.cohere.ai/v1/chat", headers=headers, json=payload)
|
31 |
+
return response.json().get("text", "No response").strip()
|
32 |
+
|
33 |
+
# Load questions from file
|
34 |
+
def load_questions():
|
35 |
+
try:
|
36 |
+
with open("questions.txt", "r") as file:
|
37 |
+
return [line.strip() for line in file if line.strip()]
|
38 |
+
except FileNotFoundError:
|
39 |
+
return []
|
40 |
+
|
41 |
+
questions_list = load_questions()
|
42 |
+
|
43 |
+
# Generate random question
|
44 |
+
def get_random_question():
|
45 |
+
return random.choice(questions_list) if questions_list else "No questions available."
|
46 |
+
|
47 |
+
# Load counter-narratives CSV
|
48 |
+
def load_counternarratives():
|
49 |
+
try:
|
50 |
+
df = pd.read_csv("counternarratives.csv")
|
51 |
+
return df
|
52 |
+
except FileNotFoundError:
|
53 |
+
print("counternarratives.csv not found.")
|
54 |
+
return pd.DataFrame(columns=["myth", "fact", "persona"])
|
55 |
+
|
56 |
+
# Generate Random Myth or Fact
|
57 |
+
def get_random_myth_or_fact():
|
58 |
+
if counternarratives.empty:
|
59 |
+
return "No myths or facts available.", "Fact-Checker", "", "", ""
|
60 |
+
|
61 |
+
# Randomly select a row from the dataframe
|
62 |
+
row = counternarratives.sample(1).iloc[0]
|
63 |
+
selected_column = random.choice(["myth", "fact"])
|
64 |
+
myth_or_fact = row[selected_column]
|
65 |
+
persona = row["persona"]
|
66 |
+
|
67 |
+
# Call the Cohere API to get the persona's response
|
68 |
+
persona_instruction = load_instruction(persona)
|
69 |
+
persona_response = call_cohere_api(persona_instruction, myth_or_fact)
|
70 |
+
|
71 |
+
# Fact-checker response logic
|
72 |
+
if selected_column == "myth":
|
73 |
+
fact_check_response = f"π **MYTH**\n\nThe fact is: {row['fact']}"
|
74 |
+
else:
|
75 |
+
fact_check_response = f"β
**FACT**\n\nIndeed, {row['fact']}"
|
76 |
+
|
77 |
+
# Return the myth/fact, update the personas, and fill the responses
|
78 |
+
return myth_or_fact, persona, "Fact-Checker", persona_response, fact_check_response
|
79 |
+
|
80 |
+
# Dynamically load persona names from instructions folder
|
81 |
+
personas = [os.path.splitext(f)[0].capitalize() for f in os.listdir("instructions") if f.endswith(".txt")]
|
82 |
+
|
83 |
+
# Gradio Interface
|
84 |
+
with gr.Blocks() as demo:
|
85 |
+
with gr.Row():
|
86 |
+
gr.Markdown("# π² **Wild Voices** β *Listening to the More-than-Human World*")
|
87 |
+
gr.Markdown("Ask questions to rivers, trees, owls, and more. Generate myths and facts, and let nature's wisdom respond.")
|
88 |
+
|
89 |
+
with gr.Row():
|
90 |
+
persona1 = gr.Dropdown(personas, label="Choose First Persona", value="Tree")
|
91 |
+
persona2 = gr.Dropdown(personas, label="Choose Second Persona", value="Crow")
|
92 |
+
|
93 |
+
with gr.Row():
|
94 |
+
user_input = gr.Textbox(label="π± Your Question", placeholder="e.g., What do you think of humans?", lines=2)
|
95 |
+
random_button = gr.Button("π² Generate Random Question")
|
96 |
+
myth_fact_button = gr.Button("π Generate Random Myth/Fact")
|
97 |
+
|
98 |
+
with gr.Row():
|
99 |
+
ask_button = gr.Button("π Submit Question")
|
100 |
+
|
101 |
+
with gr.Row():
|
102 |
+
output1 = gr.Textbox(label=f"{persona1.value} Responds")
|
103 |
+
output2 = gr.Textbox(label=f"{persona2.value} Responds")
|
104 |
+
|
105 |
+
# Button events
|
106 |
+
random_button.click(fn=get_random_question, inputs=[], outputs=[user_input])
|
107 |
+
|
108 |
+
# Myth/Fact button click event
|
109 |
+
myth_fact_button.click(
|
110 |
+
fn=get_random_myth_or_fact,
|
111 |
+
inputs=[],
|
112 |
+
outputs=[user_input, persona1, persona2, output2]
|
113 |
+
)
|
114 |
+
|
115 |
+
# Ask button for normal questions
|
116 |
+
ask_button.click(
|
117 |
+
fn=lambda p1, p2, q: (call_cohere_api(load_instruction(p1), q),
|
118 |
+
call_cohere_api(load_instruction(p2), q)),
|
119 |
+
inputs=[persona1, persona2, user_input],
|
120 |
+
outputs=[output1, output2]
|
121 |
+
)
|
122 |
+
|
123 |
+
if __name__ == "__main__":
|
124 |
+
demo.launch()
|