Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import argparse
- import json
- # Constants for configuration
- API_ENDPOINT = "http://localhost:5000/v1/completions"
- API_KEY = None # Replace with your API key if required
- DEFAULT_MODEL = "text-davinci-003"
- DEFAULT_TEMPERATURE = 0.7
- HEADERS = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {API_KEY}" if API_KEY else ""
- }
- def make_api_call(prompt, max_tokens=1000, temperature=DEFAULT_TEMPERATURE, model=DEFAULT_MODEL):
- """
- Makes a call to the API using the `requests` library.
- Args:
- prompt (str): The prompt to send to the API.
- max_tokens (int): Maximum tokens for the response.
- temperature (float): Sampling temperature.
- model (str): Model to use for the API call.
- Returns:
- str: The response text from the API.
- """
- payload = {
- "model": model,
- "prompt": prompt.strip(),
- "max_tokens": max_tokens,
- "temperature": temperature,
- }
- try:
- response = requests.post(API_ENDPOINT, headers=HEADERS, json=payload)
- response.raise_for_status()
- json_response = response.json()
- text = json_response.get("choices", [{}])[0].get("text", "").strip()
- if not text:
- raise RuntimeError("API returned an empty response.")
- return text
- except requests.exceptions.RequestException as e:
- raise RuntimeError(f"API call failed: {e}") from e
- def translate_text(source_text, source_language, target_language):
- """
- Performs a multi-step translation workflow programmatically.
- Args:
- source_text (str): The text to translate.
- source_language (str): The source language.
- target_language (str): The target language.
- Returns:
- str: The final translated text.
- """
- # Step 1: Initial Translation
- initial_prompt = f"""
- Translate the following text from {source_language} to {target_language}:
- {source_text}
- Ensure the translation is accurate, fluent, and captures all nuances of the original text. Provide only the translation in {target_language}.
- """
- initial_translation = make_api_call(initial_prompt)
- # Step 2: Refine Translation
- refine_prompt = f"""
- Improve the following translation for accuracy and fluency. Make sure it captures the original meaning and reads naturally in {target_language}:
- {initial_translation}
- """
- refined_translation = make_api_call(refine_prompt)
- # Step 3: Compare Translations
- compare_prompt = f"""
- Between the two translations below, indicate which is better based on accuracy, fluency, and naturalness in {target_language}. Respond with 'Version 1' or 'Version 2':
- Version 1: {initial_translation}
- Version 2: {refined_translation}
- """
- best_version = make_api_call(compare_prompt)
- if "Version 1" in best_version:
- return initial_translation
- elif "Version 2" in best_version:
- return refined_translation
- else:
- raise ValueError("Unexpected output from API during comparison.")
- if __name__ == "__main__":
- parser = argparse.ArgumentParser(description="Translate text from one language to another and save the result to a file.")
- parser.add_argument("infile", help="Path to the input file containing the text to translate.")
- parser.add_argument("outfile", help="Path to the output file where the translated text will be saved.")
- parser.add_argument("source_language", help="Language of the input text (e.g., 'English').")
- parser.add_argument("target_language", help="Language for the translated text (e.g., 'Spanish').")
- args = parser.parse_args()
- try:
- with open(args.infile, "r", encoding="utf-8") as infile:
- source_text = infile.read()
- translated_text = translate_text(source_text, args.source_language, args.target_language)
- with open(args.outfile, "w", encoding="utf-8") as outfile:
- outfile.write(translated_text)
- except FileNotFoundError as e:
- print(f"Error: {e}")
- exit(1)
- except RuntimeError as e:
- print(f"Error during translation: {e}")
- exit(1)
- except ValueError as e:
- print(f"Translation error: {e}")
- exit(1)
- except Exception as e:
- print(f"Unexpected error: {e}")
- exit(1)
Add Comment
Please, Sign In to add comment