Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,7 +9,6 @@ from langchain_community.graphs.networkx_graph import NetworkxEntityGraph
|
|
| 9 |
from langchain_core.prompts import ChatPromptTemplate
|
| 10 |
from langchain_groq import ChatGroq
|
| 11 |
import pandas as pd
|
| 12 |
-
from gradio_client import Client
|
| 13 |
import numpy as np
|
| 14 |
from PIL import Image as PILImage
|
| 15 |
import base64
|
|
@@ -22,7 +21,6 @@ GROQ_API_KEY = os.environ.get('GROQ_API_KEY')
|
|
| 22 |
|
| 23 |
# Set up LLM and Flux client
|
| 24 |
llm = ChatGroq(temperature=0, model_name='llama-3.1-8b-instant', groq_api_key=GROQ_API_KEY)
|
| 25 |
-
flux_client = Client("black-forest-labs/Flux.1-schnell")
|
| 26 |
|
| 27 |
def create_graph(text):
|
| 28 |
documents = [Document(page_content=text)]
|
|
@@ -58,46 +56,6 @@ def visualize_graph(graph):
|
|
| 58 |
|
| 59 |
return graph_viz_path
|
| 60 |
|
| 61 |
-
def generate_image(prompt):
|
| 62 |
-
try:
|
| 63 |
-
print(f"Generating image with prompt: {prompt}")
|
| 64 |
-
result = flux_client.predict(
|
| 65 |
-
prompt=prompt,
|
| 66 |
-
seed=0,
|
| 67 |
-
randomize_seed=True,
|
| 68 |
-
width=1024,
|
| 69 |
-
height=1024,
|
| 70 |
-
num_inference_steps=4,
|
| 71 |
-
api_name="/infer"
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
if isinstance(result, tuple) and len(result) > 0 and isinstance(result[0], str):
|
| 75 |
-
img_str = result[0]
|
| 76 |
-
|
| 77 |
-
# Fix padding if necessary
|
| 78 |
-
missing_padding = len(img_str) % 4
|
| 79 |
-
if missing_padding:
|
| 80 |
-
img_str += '=' * (4 - missing_padding)
|
| 81 |
-
|
| 82 |
-
img_data = base64.b64decode(img_str)
|
| 83 |
-
image = PILImage.open(BytesIO(img_data))
|
| 84 |
-
elif isinstance(result, tuple) and len(result) > 0 and isinstance(result[0], np.ndarray):
|
| 85 |
-
image = PILImage.fromarray((result[0] * 255).astype(np.uint8))
|
| 86 |
-
elif isinstance(result, PILImage.Image):
|
| 87 |
-
image = result
|
| 88 |
-
else:
|
| 89 |
-
raise ValueError(f"Unexpected result format from flux_client.predict: {type(result)}")
|
| 90 |
-
|
| 91 |
-
image_path = os.path.join(BASE_DIR, 'generated_image.png')
|
| 92 |
-
image.save(image_path)
|
| 93 |
-
|
| 94 |
-
print(f"Image saved to: {image_path}")
|
| 95 |
-
return image_path
|
| 96 |
-
except Exception as e:
|
| 97 |
-
print(f"Error in generate_image: {str(e)}")
|
| 98 |
-
import traceback
|
| 99 |
-
traceback.print_exc()
|
| 100 |
-
return None
|
| 101 |
|
| 102 |
def create_relations_table(graph_documents_filtered):
|
| 103 |
df = pd.DataFrame(columns=['node1', 'node2', 'relation'])
|
|
@@ -134,14 +92,7 @@ def process_text(text, question):
|
|
| 134 |
summary = llm.invoke(summary_prompt).content
|
| 135 |
print(f"Summary: {summary}")
|
| 136 |
|
| 137 |
-
|
| 138 |
-
image_path = generate_image(summary)
|
| 139 |
-
if image_path and os.path.exists(image_path):
|
| 140 |
-
print(f"Generated image saved to: {image_path}")
|
| 141 |
-
else:
|
| 142 |
-
print("Failed to generate or save image")
|
| 143 |
-
|
| 144 |
-
return answer, graph_viz_path, relations_table, summary, image_path
|
| 145 |
except Exception as e:
|
| 146 |
print(f"An error occurred in process_text: {str(e)}")
|
| 147 |
import traceback
|
|
@@ -149,10 +100,10 @@ def process_text(text, question):
|
|
| 149 |
return str(e), None, None, str(e), None
|
| 150 |
|
| 151 |
def ui_function(text, question):
|
| 152 |
-
answer, graph_viz_path, relations_table, summary
|
| 153 |
if isinstance(answer, str) and answer.startswith("An error occurred"):
|
| 154 |
return answer, None, None, answer, None
|
| 155 |
-
return answer, graph_viz_path, relations_table, summary
|
| 156 |
|
| 157 |
# Example text
|
| 158 |
example_text = """The Apollo 11 mission, launched by NASA in July 1969, was the first manned mission to land on the Moon. Commanded by Neil Armstrong and piloted by Buzz Aldrin and Michael Collins, it was the culmination of the Space Race between the United States and the Soviet Union. On July 20, 1969, Armstrong and Aldrin became the first humans to set foot on the lunar surface, while Collins orbited above in the command module."""
|
|
@@ -169,7 +120,6 @@ with gr.Blocks() as iface:
|
|
| 169 |
answer = gr.Textbox(label="Answer", lines=3, placeholder="The answer will appear here.")
|
| 170 |
relations_table = gr.Dataframe(label="Relations Table", headers=["Node 1", "Node 2", "Relation"], interactive=False)
|
| 171 |
summary = gr.Textbox(label="Summary", lines=2, placeholder="Summary of the input text will appear here.")
|
| 172 |
-
generated_image = gr.Image(label="Generated Image", type="filepath")
|
| 173 |
|
| 174 |
gr.Markdown("""
|
| 175 |
### Instructions to Use the App:
|
|
@@ -182,13 +132,13 @@ with gr.Blocks() as iface:
|
|
| 182 |
- The "Graph Visualization" will show a graphical representation of entities and their relationships in the text.
|
| 183 |
- The "Relations Table" will display extracted relationships in tabular form.
|
| 184 |
- The "Summary" field will provide a concise summary of the input text.
|
| 185 |
-
|
| 186 |
|
| 187 |
**Example:** Use the provided example paragraph for a quick demo of the app.
|
| 188 |
|
| 189 |
""")
|
| 190 |
|
| 191 |
-
gr.Button("Run").click(ui_function, inputs=[input_text, question], outputs=[answer, graph_viz, relations_table, summary
|
| 192 |
|
| 193 |
footer_text = """
|
| 194 |
<footer>
|
|
|
|
| 9 |
from langchain_core.prompts import ChatPromptTemplate
|
| 10 |
from langchain_groq import ChatGroq
|
| 11 |
import pandas as pd
|
|
|
|
| 12 |
import numpy as np
|
| 13 |
from PIL import Image as PILImage
|
| 14 |
import base64
|
|
|
|
| 21 |
|
| 22 |
# Set up LLM and Flux client
|
| 23 |
llm = ChatGroq(temperature=0, model_name='llama-3.1-8b-instant', groq_api_key=GROQ_API_KEY)
|
|
|
|
| 24 |
|
| 25 |
def create_graph(text):
|
| 26 |
documents = [Document(page_content=text)]
|
|
|
|
| 56 |
|
| 57 |
return graph_viz_path
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
def create_relations_table(graph_documents_filtered):
|
| 61 |
df = pd.DataFrame(columns=['node1', 'node2', 'relation'])
|
|
|
|
| 92 |
summary = llm.invoke(summary_prompt).content
|
| 93 |
print(f"Summary: {summary}")
|
| 94 |
|
| 95 |
+
return answer, graph_viz_path, relations_table, summary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
print(f"An error occurred in process_text: {str(e)}")
|
| 98 |
import traceback
|
|
|
|
| 100 |
return str(e), None, None, str(e), None
|
| 101 |
|
| 102 |
def ui_function(text, question):
|
| 103 |
+
answer, graph_viz_path, relations_table, summary = process_text(text, question)
|
| 104 |
if isinstance(answer, str) and answer.startswith("An error occurred"):
|
| 105 |
return answer, None, None, answer, None
|
| 106 |
+
return answer, graph_viz_path, relations_table, summary
|
| 107 |
|
| 108 |
# Example text
|
| 109 |
example_text = """The Apollo 11 mission, launched by NASA in July 1969, was the first manned mission to land on the Moon. Commanded by Neil Armstrong and piloted by Buzz Aldrin and Michael Collins, it was the culmination of the Space Race between the United States and the Soviet Union. On July 20, 1969, Armstrong and Aldrin became the first humans to set foot on the lunar surface, while Collins orbited above in the command module."""
|
|
|
|
| 120 |
answer = gr.Textbox(label="Answer", lines=3, placeholder="The answer will appear here.")
|
| 121 |
relations_table = gr.Dataframe(label="Relations Table", headers=["Node 1", "Node 2", "Relation"], interactive=False)
|
| 122 |
summary = gr.Textbox(label="Summary", lines=2, placeholder="Summary of the input text will appear here.")
|
|
|
|
| 123 |
|
| 124 |
gr.Markdown("""
|
| 125 |
### Instructions to Use the App:
|
|
|
|
| 132 |
- The "Graph Visualization" will show a graphical representation of entities and their relationships in the text.
|
| 133 |
- The "Relations Table" will display extracted relationships in tabular form.
|
| 134 |
- The "Summary" field will provide a concise summary of the input text.
|
| 135 |
+
|
| 136 |
|
| 137 |
**Example:** Use the provided example paragraph for a quick demo of the app.
|
| 138 |
|
| 139 |
""")
|
| 140 |
|
| 141 |
+
gr.Button("Run").click(ui_function, inputs=[input_text, question], outputs=[answer, graph_viz, relations_table, summary])
|
| 142 |
|
| 143 |
footer_text = """
|
| 144 |
<footer>
|