Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, render_template
|
2 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
3 |
+
import torch
|
4 |
+
|
5 |
+
# Initialize Flask app
|
6 |
+
app = Flask(__name__)
|
7 |
+
|
8 |
+
# Load the fine-tuned model and tokenizer
|
9 |
+
model_dir = "./finetune_model"
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_dir)
|
15 |
+
model.eval() # Set model to evaluation mode
|
16 |
+
|
17 |
+
# Generate headline from article
|
18 |
+
def generate_headline(article, max_length=128, num_beams=5):
|
19 |
+
# Tokenize the input article
|
20 |
+
inputs = tokenizer(article, max_length=256, truncation=True, return_tensors="pt", padding="max_length")
|
21 |
+
|
22 |
+
# Move inputs to the same device as the model
|
23 |
+
input_ids = inputs['input_ids'].to(model.device)
|
24 |
+
attention_mask = inputs['attention_mask'].to(model.device)
|
25 |
+
|
26 |
+
# Generate headline
|
27 |
+
outputs = model.generate(input_ids, attention_mask=attention_mask, max_length=max_length, num_beams=num_beams, early_stopping=True)
|
28 |
+
headline = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
29 |
+
|
30 |
+
return headline
|
31 |
+
|
32 |
+
# Home route to render the form and handle POST requests
|
33 |
+
@app.route('/', methods=['GET', 'POST'])
|
34 |
+
def home():
|
35 |
+
headline = None
|
36 |
+
if request.method == 'POST':
|
37 |
+
article = request.form.get('article')
|
38 |
+
if article:
|
39 |
+
headline = generate_headline(article)
|
40 |
+
return render_template('index.html', headline=headline)
|
41 |
+
|
42 |
+
# Run the app
|
43 |
+
if __name__ == '__main__':
|
44 |
+
app.run(host='0.0.0.0', port=5000, debug=True)
|
45 |
+
|
46 |
+
|