Views
No views yet
pip install transformers tensorflow pandas dataset tqdm1git lfs install
2git clone https://huggingface.co/nashit93/EnglishToHindiTranslationLongContext
3cd EnglishToHindiTranslationLongContext1#!/usr/bin/env python
2# coding: utf-8
3
4import tensorflow as tf
5import os
6from transformers import TFMT5ForConditionalGeneration, MT5Tokenizer
7import pandas as pd
8from datasets import Dataset
9from tqdm import tqdm
10# Set up tokenizer
11tokenizer = MT5Tokenizer.from_pretrained("google/mt5-small")
12
13
14
15
16# Function to load the model from the latest checkpoint
17def load_model(checkpoint_dir):
18 latest_checkpoint = None
19 if os.path.exists(checkpoint_dir):
20 checkpoints = [os.path.join(checkpoint_dir, d) for d in os.listdir(checkpoint_dir)]
21 checkpoints = [d for d in checkpoints if os.path.isdir(d)]
22 if checkpoints:
23 latest_checkpoint = max(checkpoints, key=os.path.getmtime)
24
25 if latest_checkpoint:
26 print("Loading model from:", latest_checkpoint)
27 return TFMT5ForConditionalGeneration.from_pretrained(latest_checkpoint)
28 else:
29 print("No checkpoint found, loading default model")
30 return TFMT5ForConditionalGeneration.from_pretrained("google/mt5-small")
31
32# Load the model
33model = load_model('model_checkpoints-small-on-1mill-dp')
34
35# Function to prepare text for prediction
36def prepare_text(text, tokenizer, max_length=200):
37 inputs = tokenizer.encode(text, return_tensors="tf", max_length=max_length, truncation=True)
38 return inputs
39
40# Function to generate prediction with adjustable settings
41def generate_prediction(text, model, tokenizer, max_length=2000, num_beams=5):
42 input_ids = prepare_text(text, tokenizer, max_length=max_length)
43 output_ids = model.generate(
44 input_ids,
45 max_length=max_length,
46 num_beams=num_beams,
47 no_repeat_ngram_size=2,
48 early_stopping=True
49 )
50 return tokenizer.decode(output_ids[0], skip_special_tokens=True)
51
52
53# Example Prediction
54sample_text = "Hi , how are you?"
55prediction = generate_prediction(sample_text, model, tokenizer)
56print("Prediction:", prediction)
57LICENSE file for details.