File size: 4,627 Bytes
da7dbd0
e58707f
38fd181
1ce1659
b73a4fc
1ce1659
b73a4fc
 
 
38fd181
 
1ce1659
b73a4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce1659
38fd181
b73a4fc
 
 
 
 
 
1ce1659
da7dbd0
 
1ce1659
da7dbd0
 
1ce1659
da7dbd0
 
38fd181
1ce1659
38fd181
1ce1659
b73a4fc
38fd181
 
 
 
 
 
 
1ce1659
da7dbd0
1ce1659
 
 
38fd181
 
da7dbd0
 
 
 
 
b73a4fc
da7dbd0
b73a4fc
da7dbd0
 
b73a4fc
da7dbd0
 
b73a4fc
da7dbd0
b73a4fc
 
38fd181
b73a4fc
 
 
 
 
00b1038
b73a4fc
 
 
 
 
 
 
38fd181
da7dbd0
 
38fd181
b73a4fc
 
 
e58707f
b73a4fc
 
38fd181
b73a4fc
 
 
38fd181
b73a4fc
 
1ce1659
b73a4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce1659
 
b73a4fc
 
 
 
1ce1659
 
b73a4fc
1ce1659
 
 
 
 
 
b73a4fc
38fd181
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import json
from typing import Optional

import openai
import pandas as pd

from src.application.config import (
    AZUREOPENAI_CLIENT,
    GPT_IMAGE_MODEL,
)


def generate_fake_text(
    text_generation_model: str,
    title: str = None,
    content: str = None,
) -> tuple[str, str]:
    """
    Generates fake news title and content using an Azure OpenAI model.

    Args:
        text_generation_model: The name of the Azure OpenAI model to use.
        title: Optional title to use as context for fake text generation.
        content: Optional content to use as context for fake text generation.

    Returns:
        A tuple containing the generated fake title and content (both strings).
        Returns empty strings if generation fails.
    """
    # Generate text using the selected models
    prompt = """Generate a random fake news tittle in this format:
---
# Title: [Fake Title]
# Content:
[Fake Content]
---
"""
    if title and content:
        prompt += """base on the following context:
        # Title: {news_title}:\n# Content: {news_content}"""
    elif title:
        prompt += """base on the following context:
        # Title: {news_title}:\n"""
    elif content:
        prompt += """base on the following context:
        # Content: {news_content}"""

    # Generate text using the text generation model
    # Generate text using the selected model
    try:
        response = AZUREOPENAI_CLIENT.chat.completions.create(
            model=text_generation_model,
            messages=[{"role": "system", "content": prompt}],
        )

        print(
            "Response from OpenAI API: ",
            response.choices[0].message.content,
        )
        fake_text = response.choices[0].message.content

    except openai.OpenAIError as e:
        print(f"Error interacting with OpenAI API: {e}")
        fake_text = ""

    if fake_text != "":
        fake_title, fake_content = extract_title_content(fake_text)
    return fake_title, fake_content


def extract_title_content(fake_news: str) -> tuple[str, str]:
    """
    Extracts the title and content from the generated fake text.

    Args:
        fake_news: The generated fake text string.

    Returns:
        A tuple containing the extracted title and content.
    """
    title = ""
    content = ""

    try:
        # Extract the title and content from the generated fake news
        title_start = fake_news.find("# Title: ") + len("# Title: ")
        title_end = fake_news.find("\n", title_start)
        if title_start != -1 and title_end != -1:
            title = fake_news[title_start:title_end]  # .strip()

        title_start = fake_news.find("\n# Content: ") + len(
            "\n# Content: ",
        )
        content = fake_news[title_start:].strip()
    except Exception as e:
        print(f"Error extracting title and content: {e}")

    return title, content


def generate_fake_image(
    title: str,
    model: str = GPT_IMAGE_MODEL,
) -> Optional[str]:
    """
    Generates a fake image URL using Azure OpenAI's image generation API.

    Args:
        title: The title to use as a prompt for image generation.
        model: The name of the Azure OpenAI image generation model to use.

    Returns:
        The URL of the generated image, or None if an error occurs.
    """
    try:
        if title:
            image_prompt = f"Generate a random image about {title}"
        else:
            image_prompt = "Generate a random image"

        result = AZUREOPENAI_CLIENT.images.generate(
            model=model,
            prompt=image_prompt,
            n=1,
        )

        image_url = json.loads(result.model_dump_json())["data"][0]["url"]
        return image_url

    except Exception as e:
        print(f"Error generating fake image: {e}")
        return None  # Return None if an error occurs


def replace_text(
    news_title: str,
    news_content: str,
    replace_df: pd.DataFrame,
) -> tuple[str, str]:
    """
    Replaces occurrences in the input title and content
        based on the provided DataFrame.

    Args:
        news_title: The input news title.
        news_content: The input news content.
        replace_df: A DataFrame with two columns:
            "Find what:" and "Replace with:".

    Returns:
        A tuple containing the modified news title and content.
    """
    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