Spaces:
Runtime error
Runtime error
Upload brain.py
Browse files
brain.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv, find_dotenv
|
2 |
+
from transformers import pipeline
|
3 |
+
from transformers import pipeline
|
4 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
5 |
+
from langchain_core.prompts import PromptTemplate
|
6 |
+
load_dotenv(find_dotenv())
|
7 |
+
|
8 |
+
|
9 |
+
def img2txt(image_path):
|
10 |
+
""" Convert image to text using Hugging Face pipeline.
|
11 |
+
Args:
|
12 |
+
image_path (str): Path to the image.
|
13 |
+
Returns:
|
14 |
+
str: The text extracted from the image.
|
15 |
+
"""
|
16 |
+
itt = pipeline(
|
17 |
+
"image-to-text",
|
18 |
+
model="Salesforce/blip-image-captioning-base"
|
19 |
+
)
|
20 |
+
text = itt(image_path)[0]["generated_text"]
|
21 |
+
print(text)
|
22 |
+
return text
|
23 |
+
|
24 |
+
|
25 |
+
def generate_story(scenario, repo_id="mistralai/Mistral-7B-Instruct-v0.2"):
|
26 |
+
""" Generate a story using image captioning and language model.
|
27 |
+
Args:
|
28 |
+
scenario (str): The scenario extracted from the image.
|
29 |
+
Returns:
|
30 |
+
str: The story generated using the scenario.
|
31 |
+
"""
|
32 |
+
llm = HuggingFaceEndpoint(
|
33 |
+
repo_id=repo_id,
|
34 |
+
temperature=0.5,
|
35 |
+
streaming=True
|
36 |
+
)
|
37 |
+
prompt_template = """
|
38 |
+
You are a kids story writer. Provide a coherent story for kids
|
39 |
+
using this simple instruction: {scenario}. The story should have a clear
|
40 |
+
beginning, middle, and end. The story should be interesting and engaging for
|
41 |
+
kids. The story should be maximum 200 words long. Do not include
|
42 |
+
any adult or polemic content.
|
43 |
+
Story:
|
44 |
+
"""
|
45 |
+
prompt = PromptTemplate.from_template(prompt_template)
|
46 |
+
story = prompt | llm
|
47 |
+
return story.invoke(input={"segmentation_results": scenario})
|
48 |
+
|
49 |
+
|
50 |
+
if __name__ == "__main__":
|
51 |
+
my_story = generate_story(img2txt("image.jpg"))
|
52 |
+
print(my_story)
|