Spaces:
Sleeping
Sleeping
@panditu1 commited on
Commit Β·
8312f3f
1
Parent(s): 806ab88
klflkd
Browse files3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546473 unmodified lines51525354555657585960616263646566673 unmodified lines71727374757677787980812 unmodified lines848586873 unmodified linesimport os# --- Model and Client Setup ---# Locally hosted model setup# Using gpt2, a small, open-source model suitable for local executionlocal_translator = pipeline("text-generation", model="openai-community/gpt2")# API-based client setup (using a token from a secret)api_token = os.environ.get("HF")api_client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1", token=api_token)# --- The Single Prediction Function ---def get_translation(simple_text, model_choice):if model_choice == "Locally Hosted":# Logic for the locally hosted model# Using a few-shot prompt to guide the text generationprompt = (f"Rephrase the following sentence into an elegant, formal, and slightly archaic English style, as if spoken by a monarch. Do not use modern slang or emojis.\n\n"f"Simple: Hello Everyone! Lets go for a ride\n"f"Elegant: Greetings, all. I propose we embark upon a most agreeable journey.\n\n"f"Simple: {simple_text}\n"f"Elegant:")# Generate the translated text. The 'text-generation' pipeline will continue the prompt.generated_text = local_translator(prompt,max_length=150,num_return_sequences=1,pad_token_id=50256 # This is needed for GPT2)[0]['generated_text']# Clean up the output to only return the "Elegant" part# This is necessary because text-generation pipelines return the full prompt + completionoutput = generated_text.split("Elegant:")[-1].strip()return outputelif model_choice == "API-Based":# Logic for the API-based modelprompt = (f"Rephrase the sentence into elegant, formal, and archaic English. Sentence: '{simple_text}'")try:response = api_client.text_generation(3 unmodified linestemperature=0.7,return_full_text=False)return response.strip()except Exception as e:return f"An error occurred with the API call: {e}"else:return "Please select a model version."# --- Gradio Interface with gr.Blocks() ---with gr.Blocks(title="Elegant English") as demo:gr.Markdown("# Elegant English: Choose Your Translator")gr.Markdown("Select a model to translate simple English into an elegant, royal style.")with gr.Row():model_dropdown = gr.Dropdown(3 unmodified lines)with gr.Row():input_textbox = gr.Textbox(lines=2, placeholder="Enter a simple sentence...", label="Simple English")output_textbox = gr.Textbox(label="Elegant English Translation")with gr.Row():submit_btn = gr.Button("Translate")submit_btn.click(fn=get_translation,2 unmodified lines)if __name__ == "__main__":demo.launch()3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647483 unmodified lines52535455565758596061626364656667686970717273743 unmodified lines7879808182838485868788899091922 unmodified lines959697983 unmodified linesimport os# --- Model and Client Setup ---# β Locally hosted model (better than GPT-2 for instruction following)# If you want something very small & fast, use distilgpt2# If you have GPU, you can switch to a small instruct-tuned model for better resultslocal_translator = pipeline("text-generation", model="distilgpt2")# β API client setup (with token)api_token = os.environ.get("HF")api_client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1", token=api_token)# --- Single Prediction Function ---def get_translation(simple_text, model_choice):if not simple_text.strip():return "β οΈ Please enter a sentence."if model_choice == "Locally Hosted":# Few-shot prompt to guide GPT-like modelprompt = ("Rephrase the following sentence into an elegant, formal, and slightly archaic English style, ""as if spoken by a monarch. Do not use modern slang or emojis.\n\n""Simple: Hello Everyone! Lets go for a ride\n""Elegant: Greetings, all. I propose we embark upon a most agreeable journey.\n\n"f"Simple: {simple_text}\nElegant:")generated = local_translator(prompt,max_new_tokens=60,pad_token_id=50256)[0]["generated_text"]# β Strip the original prompt and return only the continuationoutput = generated[len(prompt):].strip()return output if output else "(No meaningful output from local model)"elif model_choice == "API-Based":prompt = (f"Rephrase the sentence into elegant, formal, and slightly archaic English. "f"Sentence: '{simple_text}'")try:response = api_client.text_generation(3 unmodified linestemperature=0.7,return_full_text=False)# β Handle response objectif isinstance(response, list):return response[0].generated_text.strip()elif hasattr(response, "generated_text"):return response.generated_text.strip()else:return str(response)except Exception as e:return f"β API Error: {e}"else:return "β οΈ Please select a model version."# --- Gradio Interface ---with gr.Blocks(title="Elegant English") as demo:gr.Markdown("# π Elegant English Translator")gr.Markdown("Turn everyday speech into elegant, royal English.")with gr.Row():model_dropdown = gr.Dropdown(3 unmodified lines)with gr.Row():input_textbox = gr.Textbox(lines=2,placeholder="Enter a simple sentence...",label="Simple English")output_textbox = gr.Textbox(label="Elegant English Translation")with gr.Row():submit_btn = gr.Button("Translate", variant="primary")submit_btn.click(fn=get_translation,2 unmodified lines)if __name__ == "__main__":demo.launch()
app.py+46-35