aifrogsf/prompt_generation
2
1import json2import gradio as gr3import os4import langchain_openai5import langchain_core6from langchain_openai import ChatOpenAI7from langchain_core.prompts import ChatPromptTemplate8from langchain_core.output_parsers import StrOutputParser9 10def enhance_subject(subject, details):11 prompt = ChatPromptTemplate.from_messages([12 ("system", "Generate a clear and concise subject, then provide additional details using descriptive language. Ensure the response is specific and avoids ambiguity or contradictions. The subject should inspire an engaging photo that tells a story. Remove any unnecessary information and don't add any punctuation at the end of the subject."),13 ("user", "The main subject is {subject} {details}.")14 ])15 output_parser = StrOutputParser()16 model = ChatOpenAI(model="gpt-3.5-turbo")17 chain = ( prompt18 | model19 | output_parser20 )21 result = chain.invoke({"subject": subject, "details": details})22 return result23 24def load_input_fields(filepath):25 """26 Load the input fields from a JSON file.27 28 Args:29 - filepath (str): The path to the JSON file containing the input fields.30 31 Returns:32 - dict: A dictionary containing the input fields.33 """34 35 with open(filepath, "r") as file:36 input_fields = json.load(file)37 38 return input_fields39 40def create_html_string(input_text, highlight_color = "green", container_style = "border: 2px solid black; padding: 2px; font-size: 16px;" ):41 """42 Create a HTML string with specific styles applied to highlighted text within square brackets.43 44 Args:45 - input_text (str): The input text with portions to be highlighted within square brackets.46 - optional: highlight_color (str): Color for the highlighted text (e.g., "green").47 - optional: container_style (str): Any css for inline styling (e.g,, "border: 2px solid black;")48 49 Returns:50 - str: A HTML string with the applied styles.51 """52 53 # Replace the highlighted text with HTML span elements for styling54 highlighted_text = input_text.replace("[", f'<span style="color:{highlight_color}; font-weight: bold;">[').replace("]", "]</span>")55 56 # Construct the full HTML string with the provided styles57 html_string = f'<p style="{container_style}">{highlighted_text}</p>'58 59 return html_string60 61def extract_names(objects):62 return [obj['name'] for obj in objects if 'name' in obj]63 64def clearInput():65 return ""66 67def format_to_markdown(objects):68 # Skip None objects69 formatted_list = [70 f"> * **{obj.get('name', 'No Name')}** - {obj.get('description', 'No Description')}"71 for obj in objects if obj is not None and obj["name"] != "None"72 ]73 return '\n'.join(formatted_list)74 75find_filter_by_name = lambda collection, key: next((filter for filter in collection if filter['name'] == key), None)76 77def display_info(collection, key):78 markdown_text = format_to_markdown([find_filter_by_name(collection, key)])79 return gr.Markdown(markdown_text, visible=True)80 81def enhance_pipeline(isFrog, subject, details):82 if isFrog and (subject or details):83 result = enhance_subject(subject, details)84 return [gr.Textbox(visible=False), gr.Button(visible=False), gr.TextArea(visible=True, value=result)]85 elif (subject or details) and not isFrog:86 return [gr.Textbox(visible=True), gr.Button(visible=True), gr.TextArea(visible=False)]87 else:88 return [gr.Textbox(visible=False), gr.Button(visible=False), gr.TextArea(visible=False)]89 90def authenticate(pwd_input, subject, details):91 if pwd_input == os.environ.get("MAGIC_WORD"):92 result = enhance_subject(subject, details)93 return [gr.TextArea(visible=True, value=result), True, gr.Textbox(visible=False), gr.Button(visible=False)]94 else:95 raise gr.Error("You are not from our pond! Use your own LLM to add some juice to your prompt.")96 