Alpha108 commited on
Commit
745f535
·
verified ·
1 Parent(s): f0076d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -58
app.py CHANGED
@@ -1,87 +1,79 @@
1
  import streamlit as st
2
  import json
3
- from transformers import pipeline
4
- from huggingface_hub import login
5
  import os
 
6
 
7
- # Get API key from Hugging Face secrets (set in repo settings)
8
- HUGGINGFACE_TOKEN = os.environ.get("HUGGINGFACE_TOKEN")
9
- if HUGGINGFACE_TOKEN:
10
- login(token=HUGGINGFACE_TOKEN)
11
-
12
- # Load example style samples from local JSON
13
- SAMPLE_FILE = "style_samples.json"
14
- if os.path.exists(SAMPLE_FILE):
15
- with open(SAMPLE_FILE, "r") as f:
16
- style_samples = json.load(f)
17
- else:
18
- style_samples = []
19
 
20
- # Cache the pipeline for fast reload
21
  @st.cache_resource(show_spinner=False)
22
- def load_pipeline():
23
- # Try loading a fast, modern model can swap to desired model (Llama, Mixtral...)
24
- # For example: "meta-llama/Llama-2-7b-chat-hf" or any open model
25
- model_id = "google/flan-t5-base" # Replace with your favorite
26
- pipe = pipeline("text2text-generation", model=model_id)
27
- return pipe
 
 
28
 
29
- pipe = load_pipeline()
 
 
30
 
31
- # UI
32
  st.set_page_config(page_title="LinkedIn Post Generator", layout="centered")
33
- st.title("🔗 LinkedIn Post Generator (Hugging Face)")
34
- st.write("Generate high-quality LinkedIn posts using GenAI. Provide a topic, select style, and go!")
35
 
36
- with st.form("post_form"):
37
  topic = st.text_input("Post topic", "Generative AI for Business")
38
  tone = st.selectbox("Tone", ["Professional", "Friendly", "Inspirational", "Technical", "Concise"])
39
  audience = st.text_input("Audience", "Startup founders")
40
- length = st.slider("Post length (words)", 50, 500, 150, 10)
41
- style_option = st.selectbox(
42
- "Choose style sample",
43
- ["None"] + [f"Sample {i+1}" for i in range(len(style_samples))]
44
- )
45
- custom_style = st.text_area("Or paste your own style example", "")
46
- submit = st.form_submit_button("Generate LinkedIn Post")
47
 
48
- prompt_examples = ""
49
- if style_option != "None":
50
- example_idx = int(style_option.split()[1]) - 1
51
- prompt_examples += f"Example style post: {style_samples[example_idx]}\n"
52
- if custom_style.strip():
53
- prompt_examples += f"User style sample: {custom_style}\n"
54
 
55
- # Compose the prompt
56
  prompt = (
57
- f"Write a LinkedIn post on the topic '{topic}'.\n"
58
- f"Tone: {tone}.\nAudience: {audience}.\nTarget length: {length} words.\n{prompt_examples}"
59
- "Instructions: The post should engage the specified audience, use the provided style, and end with a call to action."
 
60
  )
61
 
62
- # Results area
63
- if submit:
64
  if not topic.strip():
65
- st.warning("Please enter a topic for your post.")
66
  else:
67
  with st.spinner("Generating post..."):
68
  try:
69
- result = pipe(prompt, max_new_tokens=length + 50) # Allow room for model excess
70
- gen_text = result[0]['generated_text'].strip()
71
  st.success("Here's your LinkedIn post:")
72
- st.write(gen_text)
 
73
  except Exception as e:
74
  st.error(f"Error generating post: {e}")
75
 
76
  st.markdown("---")
77
- st.write("Upload or edit your own style samples below for future runs.")
78
-
79
- uploaded_file = st.file_uploader("Upload style_samples.json (sample LinkedIn posts)", type=["json"])
80
- if uploaded_file:
81
  try:
82
- uploaded_samples = json.load(uploaded_file)
83
- with open(SAMPLE_FILE, "w") as fout:
84
- json.dump(uploaded_samples, fout)
85
- st.success(f"Sample file uploaded and saved ({len(uploaded_samples)} samples). Refresh the app to use them.")
86
  except Exception as e:
87
- st.error(f"Failed to read uploaded file: {e}")
 
1
  import streamlit as st
2
  import json
 
 
3
  import os
4
+ from transformers import pipeline
5
 
6
+ def load_style_samples(filename="style_samples.json"):
7
+ if os.path.exists(filename):
8
+ with open(filename, "r") as f:
9
+ return json.load(f)
10
+ return []
 
 
 
 
 
 
 
11
 
 
12
  @st.cache_resource(show_spinner=False)
13
+ def load_text_gen_pipeline():
14
+ model_id = "google/flan-t5-base" # Change to a larger or different supported model as needed
15
+ return pipeline(
16
+ "text2text-generation",
17
+ model=model_id,
18
+ device_map="auto",
19
+ trust_remote_code=True
20
+ )
21
 
22
+ # Load model and style samples
23
+ pipe = load_text_gen_pipeline()
24
+ style_samples = load_style_samples()
25
 
 
26
  st.set_page_config(page_title="LinkedIn Post Generator", layout="centered")
27
+ st.title("🔗 LinkedIn Post Generator (Hugging Face Space)")
28
+ st.write("Generate LinkedIn posts with custom style and parameters.")
29
 
30
+ with st.form("generate_form"):
31
  topic = st.text_input("Post topic", "Generative AI for Business")
32
  tone = st.selectbox("Tone", ["Professional", "Friendly", "Inspirational", "Technical", "Concise"])
33
  audience = st.text_input("Audience", "Startup founders")
34
+ length = st.slider("Approximate length (words)", 50, 500, 150, 10)
35
+ use_sample = st.selectbox(
36
+ "Optional: Select style sample",
37
+ ["None"] + [f"Sample {i+1}" for i in range(len(style_samples))])
38
+ custom_example = st.text_area("Or paste your own style sample (optional)")
39
+ submitted = st.form_submit_button("Generate Post")
 
40
 
41
+ style_example_text = ""
42
+ if use_sample != "None":
43
+ idx = int(use_sample.split()[1]) - 1
44
+ style_example_text += f"Example post style (imitate tone & voice): {style_samples[idx]}\n"
45
+ if custom_example.strip():
46
+ style_example_text += f"Custom example: {custom_example}\n"
47
 
 
48
  prompt = (
49
+ f"Write a LinkedIn post about '{topic}'.\n"
50
+ f"Tone: {tone}. Audience: {audience}. Target length: {length} words.\n"
51
+ f"{style_example_text}"
52
+ "Make it engaging and end with a relevant call to action."
53
  )
54
 
55
+ if submitted:
 
56
  if not topic.strip():
57
+ st.warning("Please enter a topic.")
58
  else:
59
  with st.spinner("Generating post..."):
60
  try:
61
+ generations = pipe(prompt, max_new_tokens=length + 32)
62
+ result = generations[0]["generated_text"].strip()
63
  st.success("Here's your LinkedIn post:")
64
+ st.write(result)
65
+ st.download_button("Download Post as Text", result, file_name="linkedin_post.txt")
66
  except Exception as e:
67
  st.error(f"Error generating post: {e}")
68
 
69
  st.markdown("---")
70
+ st.write("Upload your own style samples to personalize generation (overwrite previous samples):")
71
+ file = st.file_uploader("Upload style_samples.json", type=["json"])
72
+ if file is not None:
 
73
  try:
74
+ new_samples = json.load(file)
75
+ with open("style_samples.json", "w") as f:
76
+ json.dump(new_samples, f)
77
+ st.success(f"File uploaded successfully! Now {len(new_samples)} style samples saved. Reload app to use.")
78
  except Exception as e:
79
+ st.error(f"Upload failed: {e}")