Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .flake8

This file was deleted.

19 changes: 11 additions & 8 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,20 @@ jobs:

- name: Install dependencies
run: |
python -m venv venv
. venv/bin/activate
python -m pip install --upgrade pip
pip install -r requirements.txt
export PYTHONPATH=/opt/hostedtoolcache/Python/3.9.19/x64/lib/python3.9/site-packages

- name: Run tests
run: |
. venv/bin/activate
python -m unittest discover tests

- name: Lint code
run: |
. venv/bin/activate
pip install flake8
flake8 .
- name: Python Linter
uses: sunnysid3up/python-linter@master
with:
source: "prank_line_crafter/"
mypy-options: "--ignore-missing-imports --show-error-codes"
pylint-options: "--rcfile=.pylintrc"
isort-options: "-w 100"


5 changes: 5 additions & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[MASTER]
init-hook='sys.path = ["/opt/hostedtoolcache/Python/3.9.19/x64/lib/python3.9/site-packages"]'



30 changes: 25 additions & 5 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,40 @@
from prank_line_crafter.story_generator import generate_complete_story
from prank_line_crafter.sender import send_story
"""
Main module for prank_line_crafter.

This module reads names from a file, generates funny stories using LlamaAPI,
and sends them to a server.
"""

import sys

from prank_line_crafter.sender import send_story
from prank_line_crafter.story_generator import generate_complete_story


def get_names_from_file(filename):
"""Read names from the specified file."""
"""Read names from the specified file.

Args:
filename (str): The path to the file containing the names.

Returns:
list: A list of names read from the file.
"""
try:
with open(filename, 'r') as file:
with open(filename, "r", encoding="utf-8") as file: # Specify encoding
names = file.readlines()
return [name.strip() for name in names if name.strip()]
except FileNotFoundError:
print(f"The file {filename} does not exist.")
return []


def main(names_file='names.txt'):
def main(names_file="names.txt"):
"""Main function to process names and generate/send stories.

Args:
names_file (str, optional): The path to the file containing the names. Default: "names.txt".
"""
names = get_names_from_file(names_file)

for i, name in enumerate(names, start=1):
Expand Down
8 changes: 7 additions & 1 deletion prank_line_crafter/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
__version__ = '1.0.0'
"""
prank_line_crafter package.

This package provides functionality for creating and sending prank lines.
"""

__version__ = "1.0.0"
12 changes: 12 additions & 0 deletions prank_line_crafter/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
"""
Configuration module for prank_line_crafter package.

This module loads environment variables and provides configuration
constants such as API tokens and URLs.

Attributes:
LLAMA_API_TOKEN (str): The API token for LlamaAPI.
URL (str): The URL to which the stories will be sent.
"""

import os

from dotenv import load_dotenv

load_dotenv()
Expand Down
31 changes: 24 additions & 7 deletions prank_line_crafter/sender.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,39 @@
"""
Sender module for prank_line_crafter package.

This module contains functions to send generated stories to a server.

Functions:
send_story(name, story): Sends the generated story to the server.
"""

import requests

from .config import URL


def send_story(name, story):
"""Send the generated story to the server."""
"""Send the generated story to the server.

Args:
name (str): The name of the person the story is about.
story (str): The generated story content.

Returns:
str: The result of the request, indicating success or failure.
"""
data = {
"wnd_ShortTextField_670972831": name,
"wnd_RadioGroupField_714859850": "wnd_RadioGroupOption_74325105",
"wnd_LongTextField_230983133": story,
"send": "wnd_FormBlock_2860052"
"send": "wnd_FormBlock_2860052",
}

try:
response = requests.post(URL, data=data)
response = requests.post(URL, data=data, timeout=10)
response.raise_for_status() # Ensure we notice bad responses
if response.status_code == 200:
return "Request sent successfully"
else:
return f"Error in request: Status code {response.status_code}"
except requests.RequestException as e:
return f"Request failed: {e}"
return f"Error in request: Status code {response.status_code}"
except requests.RequestException as http_error:
return f"Request failed: {http_error}"
31 changes: 25 additions & 6 deletions prank_line_crafter/story_generator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
"""
Story generator module for prank_line_crafter package.

This module generates funny stories about a given name using the LlamaAPI.

Functions:
generate_complete_story(name): Generates a funny story about the given name.
"""

import requests
from llamaapi import LlamaAPI

from .config import LLAMA_API_TOKEN


Expand All @@ -7,18 +18,26 @@ def generate_complete_story(name):
llama = LlamaAPI(LLAMA_API_TOKEN)
api_request_json = {
"messages": [
{"role": "user",
"content": f"Generate a funny story about a person named {name}"}
{
"role": "user",
"content": f"Generate a funny story about a person named {name}",
}
],
"max_tokens": 500,
"stream": False
"stream": False,
}

try:
response = llama.run(api_request_json)
response.raise_for_status() # Ensure we notice bad responses
generated_text = response.json()["choices"][0]["message"]["content"]
return generated_text
except Exception as e:
print(f"Error generating story for {name}: {e}")
return "Story generation failed."
except requests.exceptions.RequestException as req_err:
print(f"Request error generating story for {name}: {req_err}")
return "Story generation failed due to request error."
except ValueError as val_err:
print(f"Value error generating story for {name}: {val_err}")
return "Story generation failed due to value error."
except KeyError as key_err:
print(f"Key error generating story for {name}: {key_err}")
return "Story generation failed due to key error."
21 changes: 9 additions & 12 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import os
import unittest
from unittest.mock import patch, MagicMock
from prank_line_crafter.story_generator import generate_complete_story
from unittest.mock import MagicMock, patch

from main import get_names_from_file
import os
from prank_line_crafter.story_generator import generate_complete_story


class TestMain(unittest.TestCase):

@patch('prank_line_crafter.story_generator.LlamaAPI.run')
@patch("prank_line_crafter.story_generator.LlamaAPI.run")
def test_generate_complete_story(self, mock_run):
# Mock the JSON response of the API call
mock_response = MagicMock()
mock_response.json.return_value = {
"choices": [
{
"message": {
"content": "Once upon a time, a person named Alice..."
}
}
{"message": {"content": "Once upon a time, a person named Alice..."}}
]
}
mock_run.return_value = mock_response
Expand All @@ -31,14 +28,14 @@ def test_generate_complete_story(self, mock_run):
def test_get_names_from_file(self):
# Get the absolute path of names.txt relative to main.py
base_dir = os.path.dirname(os.path.abspath(__file__))
names_file_path = os.path.join(base_dir, '..', 'names.txt')
names_file_path = os.path.join(base_dir, "..", "names.txt")

# Call the function to read names from the file
names = get_names_from_file(names_file_path)

# Assert that the names list matches the expected list
self.assertEqual(names, ['Alice', 'Bob', 'Charlie'])
self.assertEqual(names, ["Alice", "Bob", "Charlie"])


if __name__ == '__main__':
if __name__ == "__main__":
unittest.main()