phxdev commited on
Commit
d71cfcd
·
verified ·
1 Parent(s): 2dcd10c

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. .claude/settings.local.json +2 -1
  2. README.md +54 -232
  3. app.py +40 -32
  4. config.yaml +3 -1
  5. requirements.txt +4 -1
.claude/settings.local.json CHANGED
@@ -2,7 +2,8 @@
2
  "permissions": {
3
  "allow": [
4
  "Bash(pip install:*)",
5
- "Bash(huggingface-cli:*)"
 
6
  ],
7
  "deny": []
8
  }
 
2
  "permissions": {
3
  "allow": [
4
  "Bash(pip install:*)",
5
+ "Bash(huggingface-cli:*)",
6
+ "WebFetch(domain:huggingface.co)"
7
  ],
8
  "deny": []
9
  }
README.md CHANGED
@@ -1,232 +1,54 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- import torch
4
- import os
5
-
6
- # Initialize the text generation pipeline
7
- generator = None
8
-
9
- def initialize_model():
10
- global generator
11
- try:
12
- # Use Qwen 2.5 - state-of-the-art 2024/2025 model for document generation
13
- generator = pipeline(
14
- "text-generation",
15
- model="Qwen/Qwen2.5-1.5B-Instruct", # Latest Qwen model, perfect size for Spaces
16
- device=-1, # CPU only for compatibility
17
- torch_dtype=torch.float32,
18
- trust_remote_code=True
19
- )
20
- return "Qwen 2.5-1.5B-Instruct loaded successfully!"
21
- except Exception as e:
22
- # Fallback to smaller Qwen model
23
- try:
24
- generator = pipeline(
25
- "text-generation",
26
- model="Qwen/Qwen2.5-0.5B-Instruct",
27
- device=-1,
28
- torch_dtype=torch.float32,
29
- trust_remote_code=True
30
- )
31
- return "Fallback model (Qwen 2.5-0.5B-Instruct) loaded successfully!"
32
- except Exception as e2:
33
- # Final fallback to Phi-3 mini
34
- try:
35
- generator = pipeline(
36
- "text-generation",
37
- model="microsoft/Phi-3-mini-4k-instruct",
38
- device=-1,
39
- torch_dtype=torch.float32,
40
- trust_remote_code=True
41
- )
42
- return "Final fallback model (Phi-3-mini) loaded successfully!"
43
- except Exception as e3:
44
- return f"All modern models failed: Qwen: {str(e)}, Qwen-small: {str(e2)}, Phi-3: {str(e3)}"
45
-
46
- def generate_onepager(topic, target_audience, key_points, tone, length):
47
- if generator is None:
48
- return "Error: Model not initialized. Please wait for the model to load."
49
-
50
- # Create a structured prompt for one-pager generation
51
- length_tokens = {"Short": 200, "Medium": 400, "Long": 600}
52
- max_tokens = length_tokens.get(length, 400)
53
-
54
- # Create an optimized prompt for Qwen 2.5 instruction format
55
- prompt = f"""<|im_start|>system
56
- You are a professional document writer specializing in creating concise, well-structured one-page business documents.
57
- <|im_end|>
58
- <|im_start|>user
59
- Create a professional one-page document about "{topic}" targeted at {target_audience}.
60
-
61
- Requirements:
62
- - Tone: {tone.lower()}
63
- - Key points to include: {key_points}
64
- - Length: {length}
65
- - Format: Use clear headers and bullet points
66
- - Structure: Title, Executive Summary, Key Points, Benefits, Recommendations, Conclusion
67
-
68
- Please write the complete one-page document now.
69
- <|im_end|>
70
- <|im_start|>assistant
71
- # {topic}
72
-
73
- ## Executive Summary
74
-
75
- """
76
-
77
- try:
78
- # Generate the one-pager
79
- result = generator(
80
- prompt,
81
- max_length=len(prompt.split()) + max_tokens,
82
- num_return_sequences=1,
83
- temperature=0.8,
84
- do_sample=True,
85
- pad_token_id=generator.tokenizer.eos_token_id,
86
- eos_token_id=generator.tokenizer.eos_token_id,
87
- repetition_penalty=1.1
88
- )
89
-
90
- # Extract the generated text
91
- generated_text = result[0]['generated_text']
92
-
93
- # Clean up the output
94
- onepager = generated_text.replace(prompt, "").strip()
95
-
96
- # If output is too short, provide a structured fallback
97
- if len(onepager) < 50:
98
- onepager = create_structured_onepager(topic, target_audience, key_points, tone)
99
-
100
- return onepager
101
-
102
- except Exception as e:
103
- # Fallback to structured template
104
- return create_structured_onepager(topic, target_audience, key_points, tone)
105
-
106
- def create_structured_onepager(topic, target_audience, key_points, tone):
107
- """Create a structured one-pager when AI generation fails"""
108
-
109
- tone_styles = {
110
- "Professional": "formal and business-oriented",
111
- "Casual": "friendly and approachable",
112
- "Academic": "scholarly and research-focused",
113
- "Persuasive": "compelling and action-oriented",
114
- "Informative": "clear and educational"
115
- }
116
-
117
- style_desc = tone_styles.get(tone, "professional")
118
-
119
- template = f"""# {topic}
120
-
121
- ## Executive Summary
122
- This document provides a comprehensive overview of {topic.lower()} tailored for {target_audience.lower()}. The content is presented in a {style_desc} manner to ensure maximum impact and understanding.
123
-
124
- ## Key Points
125
-
126
- {chr(10).join([f"• {point.strip()}" for point in key_points.split(',') if point.strip()])}
127
-
128
- ## Background
129
- {topic} represents an important area that requires careful consideration and strategic thinking. Understanding the core concepts and implications is essential for {target_audience.lower()}.
130
-
131
- ## Main Content
132
- The fundamental aspects of {topic.lower()} encompass several critical areas that directly impact stakeholders. These elements work together to create a comprehensive framework for understanding and implementation.
133
-
134
- ## Benefits & Opportunities
135
- - Enhanced understanding of core concepts
136
- - Improved decision-making capabilities
137
- - Strategic advantages for implementation
138
- - Clear actionable insights
139
-
140
- ## Recommendations
141
- 1. Begin with thorough analysis of current situation
142
- 2. Develop comprehensive implementation strategy
143
- 3. Monitor progress and adjust approach as needed
144
- 4. Measure results and iterate for continuous improvement
145
-
146
- ## Conclusion
147
- {topic} offers significant opportunities for {target_audience.lower()} when approached strategically. The key points outlined above provide a solid foundation for moving forward with confidence and clarity.
148
-
149
- ---
150
- *This one-pager was generated to provide quick, actionable insights on {topic.lower()}.*"""
151
-
152
- return template
153
-
154
- # Create the Gradio interface
155
- def create_interface():
156
- with gr.Blocks(title="One-Pager Generator", theme=gr.themes.Soft()) as demo:
157
- gr.Markdown("# 📄 AI One-Pager Generator")
158
- gr.Markdown("Generate professional one-page documents on any topic using AI!")
159
-
160
- with gr.Row():
161
- with gr.Column(scale=1):
162
- topic_input = gr.Textbox(
163
- label="Topic",
164
- placeholder="e.g., Digital Marketing Strategy, Climate Change Solutions, etc.",
165
- lines=2,
166
- value="Artificial Intelligence in Healthcare"
167
- )
168
-
169
- audience_input = gr.Textbox(
170
- label="Target Audience",
171
- placeholder="e.g., Business executives, Students, General public, etc.",
172
- lines=1,
173
- value="Healthcare professionals"
174
- )
175
-
176
- keypoints_input = gr.Textbox(
177
- label="Key Points to Cover",
178
- placeholder="Enter main points separated by commas",
179
- lines=4,
180
- value="Machine learning applications, Data privacy, Cost-effectiveness, Implementation challenges"
181
- )
182
-
183
- tone_dropdown = gr.Dropdown(
184
- choices=["Professional", "Casual", "Academic", "Persuasive", "Informative"],
185
- label="Tone",
186
- value="Professional"
187
- )
188
-
189
- length_dropdown = gr.Dropdown(
190
- choices=["Short", "Medium", "Long"],
191
- label="Length",
192
- value="Medium"
193
- )
194
-
195
- generate_btn = gr.Button("🚀 Generate One-Pager", variant="primary")
196
-
197
- with gr.Column(scale=2):
198
- output_text = gr.Textbox(
199
- label="Generated One-Pager",
200
- lines=25,
201
- max_lines=35,
202
- show_copy_button=True,
203
- placeholder="Your generated one-pager will appear here..."
204
- )
205
-
206
- with gr.Row():
207
- gr.Markdown("""
208
- ### 💡 Tips for Best Results:
209
- - **Be specific** with your topic for more targeted content
210
- - **Include 3-5 key points** separated by commas
211
- - **Choose the right tone** for your intended audience
212
- - **Use descriptive audience** details (e.g., "C-level executives" vs "executives")
213
- """)
214
-
215
- # Connect the generate button to the function
216
- generate_btn.click(
217
- fn=generate_onepager,
218
- inputs=[topic_input, audience_input, keypoints_input, tone_dropdown, length_dropdown],
219
- outputs=output_text
220
- )
221
-
222
- return demo
223
-
224
- # Initialize model and launch
225
- if __name__ == "__main__":
226
- print("🚀 Starting One-Pager Generator...")
227
- print("📥 Loading AI model...")
228
- initialize_model()
229
- print("✅ Model loaded! Launching interface...")
230
-
231
- demo = create_interface()
232
- demo.launch()
 
1
+ # 📄 AI One-Pager Generator
2
+
3
+ An intelligent Gradio application that generates professional one-page documents on any topic using Hugging Face transformers.
4
+
5
+ ## Features
6
+
7
+ - **Topic-based Generation**: Create one-pagers on any subject
8
+ - **Customizable Parameters**:
9
+ - Target audience specification
10
+ - Tone selection (Professional, Casual, Academic, Persuasive, Informative)
11
+ - Length control (Short, Medium, Long)
12
+ - Key points input
13
+ - **Professional Formatting**: Structured output with title, executive summary, key points, and conclusion
14
+ - **Easy to Use**: Simple web interface powered by Gradio
15
+
16
+ ## Installation
17
+
18
+ 1. Clone this repository
19
+ 2. Install dependencies:
20
+ ```bash
21
+ pip install -r requirements.txt
22
+ ```
23
+
24
+ 3. Run the application:
25
+ ```bash
26
+ python app.py
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ 1. Enter your topic in the "Topic" field
32
+ 2. Specify your target audience
33
+ 3. List key points you want covered
34
+ 4. Select the appropriate tone and length
35
+ 5. Click "Generate One-Pager"
36
+ 6. Copy and use your generated document!
37
+
38
+ ## Deployment to Hugging Face Spaces
39
+
40
+ This app is ready to be deployed to Hugging Face Spaces:
41
+
42
+ 1. Create a new Space on Hugging Face
43
+ 2. Upload these files to your Space
44
+ 3. Your app will be automatically deployed!
45
+
46
+ ## Model Information
47
+
48
+ This application uses Qwen 2.5-Omni-7B, a state-of-the-art 2024/2025 multimodal language model with 7B parameters, specifically optimized for instruction following and high-quality document generation. Fallback models include Qwen 2.5-7B-Instruct and Qwen 2.5-1.5B-Instruct for compatibility across different hardware configurations.
49
+
50
+ **Note**: This model performs best on GPU-enabled Spaces for optimal speed and quality.
51
+
52
+ ## License
53
+
54
+ MIT License
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -9,38 +9,42 @@ generator = None
9
  def initialize_model():
10
  global generator
11
  try:
12
- # Use a modern instruction-tuned model for better document generation
 
13
  generator = pipeline(
14
  "text-generation",
15
- model="microsoft/phi-2", # Small but very capable instruction model
16
- device=-1, # CPU only for compatibility
17
- torch_dtype=torch.float32,
18
- trust_remote_code=True
 
19
  )
20
- return "Model loaded successfully!"
21
  except Exception as e:
22
- # Fallback to Flan-T5 for instruction following
23
  try:
24
- from transformers import T5ForConditionalGeneration, T5Tokenizer
25
  generator = pipeline(
26
- "text2text-generation",
27
- model="google/flan-t5-base",
28
- device=-1,
29
- torch_dtype=torch.float32
 
30
  )
31
- return "Fallback model (Flan-T5-base) loaded successfully!"
32
  except Exception as e2:
33
- # Final fallback to GPT2-medium
34
  try:
35
  generator = pipeline(
36
  "text-generation",
37
- model="gpt2-medium",
38
  device=-1,
39
- torch_dtype=torch.float32
 
40
  )
41
- return "Final fallback model (GPT2-medium) loaded successfully!"
42
  except Exception as e3:
43
- return f"All models failed: Primary: {str(e)}, Secondary: {str(e2)}, Tertiary: {str(e3)}"
44
 
45
  def generate_onepager(topic, target_audience, key_points, tone, length):
46
  if generator is None:
@@ -50,23 +54,27 @@ def generate_onepager(topic, target_audience, key_points, tone, length):
50
  length_tokens = {"Short": 200, "Medium": 400, "Long": 600}
51
  max_tokens = length_tokens.get(length, 400)
52
 
53
- # Create a better prompt for modern instruction-following models
54
- prompt = f"""Write a professional one-page document about "{topic}" for {target_audience}.
55
-
56
- Use a {tone.lower()} tone and include these key points: {key_points}
57
-
58
- Format the document with:
59
- - Clear title
60
- - Executive summary
61
- - Main sections with headers
62
- - Key benefits/recommendations
63
- - Conclusion
64
-
65
- Document:
66
-
 
 
 
67
  # {topic}
68
 
69
  ## Executive Summary
 
70
  """
71
 
72
  try:
 
9
  def initialize_model():
10
  global generator
11
  try:
12
+ # Use Qwen 2.5-Omni-7B - state-of-the-art multimodal model
13
+ device = 0 if torch.cuda.is_available() else -1
14
  generator = pipeline(
15
  "text-generation",
16
+ model="Qwen/Qwen2.5-Omni-7B",
17
+ device=device,
18
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
19
+ trust_remote_code=True,
20
+ model_kwargs={"attn_implementation": "flash_attention_2"} if torch.cuda.is_available() else {}
21
  )
22
+ return f"Qwen 2.5-Omni-7B loaded successfully on {'GPU' if device == 0 else 'CPU'}!"
23
  except Exception as e:
24
+ # Fallback to regular Qwen 7B instruct
25
  try:
26
+ device = 0 if torch.cuda.is_available() else -1
27
  generator = pipeline(
28
+ "text-generation",
29
+ model="Qwen/Qwen2.5-7B-Instruct",
30
+ device=device,
31
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
32
+ trust_remote_code=True
33
  )
34
+ return f"Fallback model (Qwen 2.5-7B-Instruct) loaded on {'GPU' if device == 0 else 'CPU'}!"
35
  except Exception as e2:
36
+ # Final fallback to 1.5B model
37
  try:
38
  generator = pipeline(
39
  "text-generation",
40
+ model="Qwen/Qwen2.5-1.5B-Instruct",
41
  device=-1,
42
+ torch_dtype=torch.float32,
43
+ trust_remote_code=True
44
  )
45
+ return "Final fallback model (Qwen 2.5-1.5B-Instruct) loaded on CPU!"
46
  except Exception as e3:
47
+ return f"All models failed: Omni: {str(e)}, 7B: {str(e2)}, 1.5B: {str(e3)}"
48
 
49
  def generate_onepager(topic, target_audience, key_points, tone, length):
50
  if generator is None:
 
54
  length_tokens = {"Short": 200, "Medium": 400, "Long": 600}
55
  max_tokens = length_tokens.get(length, 400)
56
 
57
+ # Create an optimized prompt for Qwen 2.5 instruction format
58
+ prompt = f"""<|im_start|>system
59
+ You are a professional document writer specializing in creating concise, well-structured one-page business documents.
60
+ <|im_end|>
61
+ <|im_start|>user
62
+ Create a professional one-page document about "{topic}" targeted at {target_audience}.
63
+
64
+ Requirements:
65
+ - Tone: {tone.lower()}
66
+ - Key points to include: {key_points}
67
+ - Length: {length}
68
+ - Format: Use clear headers and bullet points
69
+ - Structure: Title, Executive Summary, Key Points, Benefits, Recommendations, Conclusion
70
+
71
+ Please write the complete one-page document now.
72
+ <|im_end|>
73
+ <|im_start|>assistant
74
  # {topic}
75
 
76
  ## Executive Summary
77
+
78
  """
79
 
80
  try:
config.yaml CHANGED
@@ -7,4 +7,6 @@ sdk_version: 4.44.0
7
  app_file: app.py
8
  pinned: false
9
  license: mit
10
- short_description: Generate professional one-page documents on any topic using AI
 
 
 
7
  app_file: app.py
8
  pinned: false
9
  license: mit
10
+ suggested_hardware: t4-small
11
+ suggested_storage: small
12
+ short_description: Generate professional one-page documents using Qwen 2.5-Omni-7B
requirements.txt CHANGED
@@ -2,4 +2,7 @@ gradio
2
  transformers
3
  torch
4
  huggingface_hub
5
- tokenizers
 
 
 
 
2
  transformers
3
  torch
4
  huggingface_hub
5
+ tokenizers
6
+ flash-attn
7
+ accelerate
8
+ bitsandbytes