lexicalspace commited on
Commit
90983f1
·
verified ·
1 Parent(s): db2b363

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -44
app.py CHANGED
@@ -1,94 +1,98 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
3
 
4
- # Use Qwen 2.5 Coder 32B (Excellent for code & JSON)
5
- # We will access it via the Chat API to avoid "Task not supported" errors.
6
- REPO_ID = "Qwen/Qwen2.5-Coder-32B-Instruct"
7
- client = InferenceClient()
 
 
 
 
8
 
9
  def generate_seo(code_snippet, file_type):
10
  """
11
- Analyzes code and generates SEO metadata + JSON-LD using Chat API.
12
  """
13
  if not code_snippet.strip():
14
- return "Please paste some code first."
15
 
16
- # 1. Define the System Prompt (The instructions)
17
  system_instruction = f"""
18
- You are an expert SEO specialist and Software Engineer.
19
- Analyze the user's {file_type} code.
20
-
21
- Output Format requirements:
22
- 1. Title: A clickable, SEO-optimized title tag (max 60 chars).
23
- 2. Meta Description: A summary for search engines (max 160 chars).
24
- 3. Keywords: 5-8 comma-separated high-value keywords.
25
- 4. JSON-LD: A valid <script type="application/ld+json"> block.
26
- - If Python: use Schema.org 'SoftwareSourceCode'.
27
- - If HTML: use Schema.org 'WebPage' or 'TechArticle'.
28
 
29
- Strictly follow this output format (Markdown):
30
 
 
31
  ## SEO Metadata
32
- **Title:** [Title Here]
33
- **Description:** [Description Here]
34
- **Keywords:** [Keywords Here]
35
 
36
  ## JSON-LD Structured Data
37
  ```json
38
- [Insert strictly valid JSON code here, no comments]
 
 
39
  ```
40
  """
41
 
42
- # 2. Define the User Message (The Code)
43
- user_message = f"Here is the {file_type} code:\n\n{code_snippet}"
44
 
45
  try:
46
- # 3. Use chat_completion (matches 'conversational' task)
47
  response = client.chat_completion(
48
- model=REPO_ID,
49
  messages=[
50
  {"role": "system", "content": system_instruction},
51
  {"role": "user", "content": user_message}
52
  ],
53
- max_tokens=1024,
54
- temperature=0.3
55
  )
56
-
57
- # Extract the actual message content
58
  return response.choices[0].message.content
59
 
60
  except Exception as e:
61
- # Fallback error handling
62
- return f"Error: {str(e)}\n\nTry switching the model in the code to 'meta-llama/Meta-Llama-3-8B-Instruct' if this persists."
 
 
 
 
 
 
 
 
63
 
64
- # Design the UI
65
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
66
  gr.Markdown(
67
  """
68
- # 🚀 AI Code-to-SEO Generator
69
- Paste your **Python** or **HTML** code below to generate optimized meta tags and JSON-LD Schema.
70
  """
71
  )
72
 
73
  with gr.Row():
74
- with gr.Column():
75
- input_type = gr.Radio(["python", "html"], label="File Type", value="python")
76
- code_input = gr.Code(language="python", label="Paste Code Here", lines=10)
77
- submit_btn = gr.Button("Generate SEO & JSON-LD", variant="primary")
78
 
79
- with gr.Column():
80
- output_markdown = gr.Markdown(label="Generated SEO Strategy")
 
81
 
82
- # Update syntax highlighting dynamically
83
  input_type.change(lambda x: gr.Code(language=x), inputs=input_type, outputs=code_input)
84
 
85
- # Run logic
86
  submit_btn.click(
87
  fn=generate_seo,
88
  inputs=[code_input, input_type],
89
  outputs=output_markdown
90
  )
91
 
92
- # Launch
93
  if __name__ == "__main__":
94
  demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import os
4
 
5
+ # 1. SETUP: Get the token from the Space secrets
6
+ # This fixes the "Auth" error by using your private key
7
+ hf_token = os.getenv("HF_TOKEN")
8
+
9
+ # Initialize the client with your token
10
+ # We use Qwen 2.5 Coder 32B. It is the best open model for this task.
11
+ model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
12
+ client = InferenceClient(api_key=hf_token)
13
 
14
  def generate_seo(code_snippet, file_type):
15
  """
16
+ Generates SEO and JSON-LD using the Authenticated Client.
17
  """
18
  if not code_snippet.strip():
19
+ return "⚠️ Error: Please paste some code first."
20
 
21
+ # SEO Prompt
22
  system_instruction = f"""
23
+ You are an expert Technical SEO Specialist. Analyze the user's {file_type} code.
 
 
 
 
 
 
 
 
 
24
 
25
+ Your Goal: Generate Google-compliant JSON-LD structured data and SEO meta tags.
26
 
27
+ Output Format (Strict Markdown):
28
  ## SEO Metadata
29
+ **Title:** [Engaging Title, max 60 chars]
30
+ **Description:** [Summary including keywords, max 160 chars]
31
+ **Keywords:** [5-8 comma-separated keywords]
32
 
33
  ## JSON-LD Structured Data
34
  ```json
35
+ [Insert VALID JSON-LD here.
36
+ - If Python: Use schema.org/SoftwareSourceCode
37
+ - If HTML: Use schema.org/WebPage or schema.org/TechArticle]
38
  ```
39
  """
40
 
41
+ user_message = f"Analyze this {file_type} code:\n\n{code_snippet}"
 
42
 
43
  try:
44
+ # Chat Completion API (Reliable with Token)
45
  response = client.chat_completion(
46
+ model=model_id,
47
  messages=[
48
  {"role": "system", "content": system_instruction},
49
  {"role": "user", "content": user_message}
50
  ],
51
+ max_tokens=1500,
52
+ temperature=0.2 # Low temp for precise JSON
53
  )
 
 
54
  return response.choices[0].message.content
55
 
56
  except Exception as e:
57
+ # detailed error logging for the UI
58
+ error_msg = str(e)
59
+ if "401" in error_msg:
60
+ return "🔒 Authentication Error: Please check that you added 'HF_TOKEN' to your Space Secrets."
61
+ elif "429" in error_msg:
62
+ return "⏳ Rate Limit: The free model is busy. Please wait 1 minute and try again."
63
+ elif "504" in error_msg:
64
+ return "⏱️ Timeout: The code snippet might be too long. Try a shorter piece of code."
65
+ else:
66
+ return f"❌ System Error: {error_msg}"
67
 
68
+ # UI Layout
69
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
70
  gr.Markdown(
71
  """
72
+ # SEO & JSON-LD Generator (Authenticated)
73
+ **Status:** Connected to Qwen 2.5 Coder
74
  """
75
  )
76
 
77
  with gr.Row():
78
+ with gr.Column(scale=1):
79
+ input_type = gr.Radio(["python", "html"], label="Select File Type", value="python")
80
+ code_input = gr.Code(language="python", label="Paste Code Here", lines=15)
81
+ submit_btn = gr.Button("Generate SEO Data", variant="primary", size="lg")
82
 
83
+ with gr.Column(scale=1):
84
+ # This component displays the result
85
+ output_markdown = gr.Markdown(label="Results will appear here...")
86
 
87
+ # Dynamic syntax highlighting
88
  input_type.change(lambda x: gr.Code(language=x), inputs=input_type, outputs=code_input)
89
 
90
+ # Button Click Action
91
  submit_btn.click(
92
  fn=generate_seo,
93
  inputs=[code_input, input_type],
94
  outputs=output_markdown
95
  )
96
 
 
97
  if __name__ == "__main__":
98
  demo.launch()