Spaces:
Sleeping
Sleeping
import openai | |
from dotenv import load_dotenv | |
import os | |
load_dotenv() | |
AZURE_OPENAI_API_KEY = os.getenv('AZURE_OPENAI_API_KEY') | |
AZURE_OPENAI_ENDPOINT = os.getenv('AZURE_OPENAI_ENDPOINT') | |
AZURE_OPENAI_API_VERSION = os.getenv('AZURE_OPENAI_API_VERSION') | |
client = openai.AzureOpenAI( | |
api_version = AZURE_OPENAI_API_VERSION, | |
api_key = AZURE_OPENAI_API_KEY, | |
azure_endpoint = AZURE_OPENAI_ENDPOINT, | |
) | |
def generate_content(text_generation_model, image_generation_model, title, content): | |
# Generate text using the selected models | |
full_content = "" | |
input_type = "" | |
if title and content: | |
full_content = title + "\n" + content | |
input_type = "title and content" | |
elif title: | |
full_content = title | |
input_type = "title" | |
elif content: | |
full_content = title | |
input_type = "content" | |
# Generate text using the text generation model | |
generated_text = generate_text(text_generation_model, full_content, input_type) | |
return title, generated_text | |
def generate_text(model, full_context, input_type): | |
# Generate text using the selected model | |
if input_type == "": | |
prompt = "Generate a random fake news article" | |
else: | |
prompt = f"Generate a fake news article (title and content) based on the following: # Title: {input_type}:\n\n# Content: {full_context}" | |
try: | |
response = client.chat.completions.create( | |
model=model, | |
messages = [{"role": "system", "content": prompt}], | |
) | |
print("Response from OpenAI API: ", response.choices[0].message.content) | |
return response.choices[0].message.content | |
except openai.OpenAIError as e: | |
print(f"Error interacting with OpenAI API: {e}") | |
return "An error occurred while processing your request." | |
def replace_text(news_title, news_content, replace_df): | |
""" | |
Replaces occurrences in the input text based on the provided DataFrame. | |
Args: | |
text: The input text. | |
replace_df: A pandas DataFrame with two columns: "find_what" and "replace_with". | |
Returns: | |
The text after all replacements have been made. | |
""" | |
for _, row in replace_df.iterrows(): | |
find_what = row["Find what:"] | |
replace_with = row["Replace with:"] | |
news_content = news_content.replace(find_what, replace_with) | |
news_title = news_title.replace(find_what, replace_with) | |
return news_title, news_content |