Hugo commited on
Commit
e873032
·
1 Parent(s): 5daac35

gradio support

Browse files
Files changed (2) hide show
  1. app.py +36 -28
  2. app_streamlit.py +103 -0
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import streamlit as st
2
  from peft import PeftModel
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import os
@@ -15,7 +15,6 @@ openai_api_key = os.environ.get('OPENAI_API_KEY')
15
 
16
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17
 
18
- @st.cache_resource
19
  def load_model():
20
  base_model = AutoModelForCausalLM.from_pretrained(base_model_id, use_auth_token=hf_token)
21
  model = PeftModel.from_pretrained(base_model, model_id, use_auth_token=hf_token).to(device)
@@ -73,31 +72,40 @@ def process_prompt(tokenizer, content, video_summary = '', guidelines = None):
73
  prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
74
  return prompt
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- st.title("Article Headline Writer")
78
- st.write("Write a catchy headline from content and video summary.")
79
-
80
- # Inputs for content and video summary
81
- content = st.text_area("Enter the article content:", placeholder="Type the main content of the article here...")
82
- video_summary = st.text_area("Enter the summary of the article's accompanying video (optional):", placeholder="Type the summary of the video related to the article...")
 
 
 
 
 
83
 
84
- if st.button("Generate Headline"):
85
- if content.strip():
86
- if not video_summary.strip():
87
- video_summary = ''
88
- prompt = process_prompt(tokenizer, content, video_summary, guidelines)
89
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(device)
90
-
91
- st.write("### Generated 5 Potential Headlines:")
92
- for i in range(5):
93
- st.write(f"### Headline {i+1}")
94
- outputs = model.generate(**inputs,
95
- max_new_tokens=60,
96
- num_return_sequences=1,
97
- do_sample=True,
98
- temperature=0.7)
99
- response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
100
- response = response.replace('"', '')
101
- st.write(f"{response}")
102
- else:
103
- st.write("Please enter a valid prompt.")
 
1
+ import gradio as gr
2
  from peft import PeftModel
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import os
 
15
 
16
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17
 
 
18
  def load_model():
19
  base_model = AutoModelForCausalLM.from_pretrained(base_model_id, use_auth_token=hf_token)
20
  model = PeftModel.from_pretrained(base_model, model_id, use_auth_token=hf_token).to(device)
 
72
  prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
73
  return prompt
74
 
75
+ def generate_headlines(content, video_summary):
76
+ if not content.strip():
77
+ return "Please enter valid article content."
78
+
79
+ if not video_summary.strip():
80
+ video_summary = ''
81
+
82
+ prompt = process_prompt(tokenizer, content, video_summary, guidelines)
83
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(device)
84
+
85
+ headlines = []
86
+ for i in range(5):
87
+ outputs = model.generate(**inputs,
88
+ max_new_tokens=60,
89
+ num_return_sequences=1,
90
+ do_sample=True,
91
+ temperature=0.7)
92
+ response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
93
+ response = response.replace('"', '')
94
+ headlines.append(f"Headline {i+1}: {response}")
95
+
96
+ return "\n\n".join(headlines)
97
 
98
+ # Create Gradio interface
99
+ demo = gr.Interface(
100
+ fn=generate_headlines,
101
+ inputs=[
102
+ gr.Textbox(label="Article Content", placeholder="Type the main content of the article here..."),
103
+ gr.Textbox(label="Video Summary (Optional)", placeholder="Type the summary of the video related to the article...")
104
+ ],
105
+ outputs=gr.Textbox(label="Generated Headlines"),
106
+ title="Article Headline Writer",
107
+ description="Write catchy headlines from content and video summary."
108
+ )
109
 
110
+ if __name__ == "__main__":
111
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_streamlit.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from peft import PeftModel
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import os
5
+ import os.path
6
+ import pickle
7
+ import torch
8
+ from openai import OpenAI
9
+
10
+ base_model_id = "meta-llama/Llama-3.2-3B-Instruct"
11
+ model_id = "HiGenius/Headline-Generation-Model"
12
+
13
+ hf_token = os.environ.get('HF_TOKEN')
14
+ openai_api_key = os.environ.get('OPENAI_API_KEY')
15
+
16
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17
+
18
+ @st.cache_resource
19
+ def load_model():
20
+ base_model = AutoModelForCausalLM.from_pretrained(base_model_id, use_auth_token=hf_token)
21
+ model = PeftModel.from_pretrained(base_model, model_id, use_auth_token=hf_token).to(device)
22
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id, use_auth_token=hf_token)
23
+ tokenizer.pad_token = tokenizer.eos_token
24
+ tokenizer.padding_side='left'
25
+ tokenizer.truncation_side="left"
26
+
27
+ return tokenizer, model
28
+
29
+ def summarize_content(content):
30
+ client = OpenAI(api_key=openai_api_key)
31
+ response = client.chat.completions.create(
32
+ model="gpt-4o",
33
+ messages=[
34
+ {"role": "system", "content": "Summarize the following article content concisely while preserving key information:"},
35
+ {"role": "user", "content": content}
36
+ ],
37
+ max_tokens=600,
38
+ temperature=0.3
39
+ )
40
+ return response.choices[0].message.content
41
+
42
+ tokenizer, model = load_model()
43
+
44
+ guideline_path = "./guidelines.txt"
45
+ with open(guideline_path, 'r', encoding='utf-8') as f:
46
+ guidelines = f.read()
47
+
48
+ def process_prompt(tokenizer, content, video_summary = '', guidelines = None):
49
+ # Check token lengths
50
+ content_tokens = len(tokenizer.encode(content))
51
+ total_tokens = content_tokens
52
+ if video_summary:
53
+ total_tokens += len(tokenizer.encode(video_summary))
54
+
55
+ if content_tokens > 850 or total_tokens > 900:
56
+ content = summarize_content(content)
57
+
58
+ if guidelines:
59
+ system_prompt = "You are a helpful assistant that writes engaging headlines. To maximize engagement, you may follow these proven guidelines:\n" + guidelines
60
+ else:
61
+ system_prompt = "You are a helpful assistant that writes engaging headlines."
62
+
63
+ user_prompt = (
64
+ f"Below is an article and its accompanying video summary:\n\n"
65
+ f"Article Content:\n{content}\n\n"
66
+ f"Video Summary:\n{'None' if video_summary == '' else video_summary}\n\n"
67
+ f"Write ONLY a single engaging headline that accurately reflects the article. Do not include any additional text, explanations, or options."
68
+ )
69
+ messages = [
70
+ {"role": "system", "content": system_prompt},
71
+ {"role": "user", "content": user_prompt},
72
+ ]
73
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
74
+ return prompt
75
+
76
+
77
+ st.title("Article Headline Writer")
78
+ st.write("Write a catchy headline from content and video summary.")
79
+
80
+ # Inputs for content and video summary
81
+ content = st.text_area("Enter the article content:", placeholder="Type the main content of the article here...")
82
+ video_summary = st.text_area("Enter the summary of the article's accompanying video (optional):", placeholder="Type the summary of the video related to the article...")
83
+
84
+ if st.button("Generate Headline"):
85
+ if content.strip():
86
+ if not video_summary.strip():
87
+ video_summary = ''
88
+ prompt = process_prompt(tokenizer, content, video_summary, guidelines)
89
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(device)
90
+
91
+ st.write("### Generated 5 Potential Headlines:")
92
+ for i in range(5):
93
+ st.write(f"### Headline {i+1}")
94
+ outputs = model.generate(**inputs,
95
+ max_new_tokens=60,
96
+ num_return_sequences=1,
97
+ do_sample=True,
98
+ temperature=0.7)
99
+ response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
100
+ response = response.replace('"', '')
101
+ st.write(f"{response}")
102
+ else:
103
+ st.write("Please enter a valid prompt.")