| import gradio as gr |
| from transformers import pipeline |
|
|
| |
| classifier = pipeline("text-classification", model="huggingface/CodeBERTa-language-id") |
|
|
| def detect_code_language(code): |
| """ |
| Detect the programming language of the provided code snippet |
| """ |
| if not code.strip(): |
| return "Please enter some code!" |
| |
| try: |
| result = classifier(code)[0] |
| language = result['label'] |
| confidence = result['score'] |
| |
| |
| output = f"Detected Language: **{language.upper()}**\n\n" |
| output += f"Confidence: {confidence:.2%}\n\n" |
| output += "---\n\n" |
| output += f"The code snippet appears to be written in **{language}** " |
| output += f"with {confidence:.1%} confidence." |
| |
| return output |
| except Exception as e: |
| return f"Error: {str(e)}" |
|
|
| |
| examples = [ |
| ["""def hello_world(): |
| print("Hello, World!") |
| return True"""], |
| ["""function helloWorld() { |
| console.log("Hello, World!"); |
| return true; |
| }"""], |
| ["""public class HelloWorld { |
| public static void main(String[] args) { |
| System.out.println("Hello, World!"); |
| } |
| }"""], |
| ["""#include <iostream> |
| using namespace std; |
| |
| int main() { |
| cout << "Hello, World!" << endl; |
| return 0; |
| }"""], |
| ["""package main |
| import "fmt" |
| |
| func main() { |
| fmt.Println("Hello, World!") |
| }"""] |
| ] |
|
|
| |
| demo = gr.Interface( |
| fn=detect_code_language, |
| inputs=gr.Code( |
| label="Paste Your Code Here", |
| language="python", |
| lines=10 |
| ), |
| outputs=gr.Markdown(label="Detection Result"), |
| title="Code Language Detector", |
| description="Paste any code snippet and I'll identify which programming language it's written in!", |
| examples=examples, |
| theme=gr.themes.Soft(), |
| article="Powered by Hugging Face's CodeBERTa model. Supports Python, JavaScript, Java, C++, Go, PHP, Ruby, and more!" |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch() |