neovalle commited on
Commit
3efcf63
Β·
verified Β·
1 Parent(s): 5302022

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -121
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
- counternarratives = load_counternarratives()
57
-
58
- # Generate Random Myth or Fact
59
- def get_random_myth_or_fact():
60
- if counternarratives.empty:
61
- return "No myths or facts available.", "Fact-Checker", "", ""
62
-
63
- row = counternarratives.sample(1).iloc[0]
64
- selected_column = random.choice(["myth", "fact"])
65
- myth_or_fact = row[selected_column]
66
- persona = row["persona"]
67
-
68
- # Set Persona 1 to the one in the myth/fact and Persona 2 to "Fact-Checker"
69
- if selected_column == "myth":
70
- fact_check_response = f"πŸ›‘ **MYTH**\n\nThe fact is: {row['fact']}"
71
- else:
72
- fact_check_response = f"βœ… **FACT**\n\nIndeed, {row['fact']}"
73
-
74
- # Return responses and personas for the UI
75
- return myth_or_fact, persona, "Fact-Checker", fact_check_response
76
-
77
- # Dynamically load persona names from instructions folder
78
- personas = [os.path.splitext(f)[0].capitalize() for f in os.listdir("instructions") if f.endswith(".txt")]
79
-
80
- # Gradio Interface
81
- with gr.Blocks() as demo:
82
- with gr.Row():
83
- gr.Markdown("# 🌲 **Wild Voices** β€” *Listening to the More-than-Human World*")
84
- gr.Markdown("Ask questions to rivers, trees, owls, and more. Generate myths and facts, and let nature's wisdom respond.")
85
-
86
- with gr.Row():
87
- persona1 = gr.Dropdown(personas, label="Choose First Persona", value="Tree")
88
- persona2 = gr.Dropdown(personas, label="Choose Second Persona", value="Crow")
89
-
90
- with gr.Row():
91
- user_input = gr.Textbox(label="🌱 Your Question", placeholder="e.g., What do you think of humans?", lines=2)
92
- random_button = gr.Button("🎲 Generate Random Question")
93
- myth_fact_button = gr.Button("πŸ” Generate Random Myth/Fact")
94
-
95
- with gr.Row():
96
- ask_button = gr.Button("🌎 Submit Question")
97
-
98
- with gr.Row():
99
- output1 = gr.Textbox(label=f"{persona1.value} Responds")
100
- output2 = gr.Textbox(label=f"{persona2.value} Responds")
101
-
102
- # Button events
103
- random_button.click(fn=get_random_question, inputs=[], outputs=[user_input])
104
-
105
- # Myth/Fact button click event
106
- myth_fact_button.click(
107
- fn=get_random_myth_or_fact,
108
- inputs=[],
109
- outputs=[user_input, persona1, persona2, output2]
110
- )
111
-
112
- # Ask button for normal questions
113
- ask_button.click(
114
- fn=lambda p1, p2, q: (call_cohere_api(load_instruction(p1), q),
115
- call_cohere_api(load_instruction(p2), q)),
116
- inputs=[persona1, persona2, user_input],
117
- outputs=[output1, output2]
118
- )
119
-
120
- if __name__ == "__main__":
121
- demo.launch()
 
 
 
 
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()